[英]Adding functionality to directly import certain functions from python sub-packages
Consider a regular python package with following fixed structure考虑具有以下固定结构的常规 python package
myPackage/
├──__init__.py
├──basic/
│ ├──__init__.py
│ ├──basicOne/
│ │ ├──__init__.py
│ │ ├──f1.py
│ │ └──f2.py
│ ├──a1.py
│ └──a2.py
└──README.md
If one wants to import some function foo()
in f1.py
, and roo()
in a1.py
, then one can use standard commands如果想在a1.py
中导入一些 function foo()
和f1.py
中的roo()
,那么可以使用标准命令
from myPackage.basic.basicOne import f1
f1.foo()
and和
from myPackage.basic import a1
a1.roo()
Suppose one wants to add a feature where function foo()
and roo()
can also be called this way假设想要添加一个特性,其中 function foo()
和roo()
也可以这样调用
import myPackage as myPack
myPack.foo()
myPack.roo()
then what additional code should one write in the package?那么应该在 package 中编写哪些附加代码? If such additional code is written, would it interfere with distributing and installing the top-level package, myPackage
.如果编写了这样的附加代码,是否会干扰顶级 package、 myPackage
的分发和安装。 Since there are many methods to distribute, lets fix the method to the one given in Packaging Python Projects .由于要分发的方法很多,让我们将方法修复为Packaging Python Projects中给出的方法。
Just go to the most top level __init__.py
file and import what you need there:只需 go 到最顶层的__init__.py
文件并在那里导入您需要的内容:
from .basic.basicOne.f1 import foo
from .basic.a1 import roo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.