[英]How do I structure my Python package?
I have most of my code in project.py which requires a second file, otherfile.py. 我的大部分代码都在project.py中,它需要第二个文件otherfile.py。 Currently I'm just installing them as two separate modules with the same
setup.py
(with the py_modules variable) but I figured it's about time to package things up properly since project.py is growing and I may need split it up further. 目前,我只是将它们安装为具有相同
setup.py
(带有py_modules变量)的两个单独的模块,但我认为现在是时候将其正确打包了,因为project.py正在增长,我可能需要将其进一步分解。
The user only ever needs to interact with some classes and functions in project.py so in order to keep compatibility I wanted to use the following structure: 用户只需要与project.py中的某些类和函数进行交互,因此为了保持兼容性,我想使用以下结构:
project/
__init__.py # (renamed from project.py)
otherfile.py
However I've read that __init__.py
should be kept almost empty. 但是我读过
__init__.py
应该保持几乎为空。 Another alternative would be: 另一种选择是:
project/
__init__.py
project.py
otherfile.py
and to import everything from project.py
that the user can see into __init__.py
because I'd like to avoid adding an extra namespace for the user: 并将用户可以看到的
project.py
中的所有内容导入__init__.py
因为我想避免为用户添加额外的名称空间:
import project.project
I'm not sure it really matters but I'd like to do things 'The-Right-Way'. 我不确定这是否真的很重要,但是我想做“正确的道路”。
You could use the second structure, but in your __init__.py
, simply have... 您可以使用第二种结构,但是在
__init__.py
,只需...
from .project import PublicClass1
from .project import PublicClass2
from .project import PUBLIC_CONSTANT_A
...
Basically, only importing in __init__.py
what you actually want to be public, while keeping __init__.py
mostly free of code logic. 基本上,仅在
__init__.py
导入您真正希望公开的内容,同时使__init__.py
基本上没有代码逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.