Python:缩短我的包装的导入语句
我的软件包具有以下文件夹结构:
pkg/
├─ pkg/
│ ├─ module1/
│ | ├─ __init__.py
│ | ├─ classB.py
│ | └─ functionB.py
│ ├─ __init__.py
│ ├─ classA.py
│ └─ functionA.py
├─ setup.py
└─ .gitignore
每个Python文件classx.py
和functionx.py
包含一个单个类或功能,其名称与文件本身相同。例如,classa.py
包含def classa(object):[...]
,什么都没有。有时,我将课程和功能放入这样的单独文件中,因为它们往往会变得巨大。
使用pip install -e。
以开发器模式安装软件包后,我必须这样导入:
from pkg.classA import classA
from pkg.functionA import functionA
from pkg.module1.classB import classB
from pkg.module1.functionB import functionB
我更喜欢这样导入: (其他人必须使用我的软件包,所以必须很好)
from pkg import classA, functionA
from pkg.module1 import classB, functionB
我设法通过编辑pkg/pkg/__ init __. py
:
from pkg.classA import classA
from pkg.functionA import functionA
和编辑pkg/pkg/module1,设法 启用了上述内容。 /__ INIT __。py
:
from pkg.module1.classB import classB
from pkg.module1.functionB import functionB
我的解决方案非常糟糕。有没有更好的方法来做到这一点,或者我应该将大型的类和功能放在一个(可能是巨大的)python文件中?
My package has the following folder structure:
pkg/
├─ pkg/
│ ├─ module1/
│ | ├─ __init__.py
│ | ├─ classB.py
│ | └─ functionB.py
│ ├─ __init__.py
│ ├─ classA.py
│ └─ functionA.py
├─ setup.py
└─ .gitignore
Each of the python files classX.py
and functionX.py
contains a single class or function with the same name as the file itself. For example, classA.py
contains def classA(object): [...]
and nothing else. Sometimes, I put classes and functions into separate files like that because they tend to become huge.
After I install my package in developer mode with pip install -e .
, I have to import like this:
from pkg.classA import classA
from pkg.functionA import functionA
from pkg.module1.classB import classB
from pkg.module1.functionB import functionB
I would prefer to import like this instead:
(other people have to use my package, so it has to be nice)
from pkg import classA, functionA
from pkg.module1 import classB, functionB
I managed to enable the above by editing pkg/pkg/__init__.py
:
from pkg.classA import classA
from pkg.functionA import functionA
and by editing pkg/pkg/module1/__init__.py
:
from pkg.module1.classB import classB
from pkg.module1.functionB import functionB
My solution is horribly inelegant. Is there a better way to do this or am I supposed to just put the huge classes and functions together into one (possibly enormous) python file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的轨道正确,只需要更多的优化即可。
编辑文件
pkg/pkg/__ init __。py
as和file
pkg/pkg/module1/__ init __. py
,因为这将适用于您,并且有点清洁。
You are on right track, just need a little bit more optimization.
edit file
pkg/pkg/__init__.py
asand file
pkg/pkg/module1/__init__.py
asThis will work for you, and a little bit cleaner.