[英]Python Package Folder Structure
I have been researching how to build the folder structure for a custom python package.我一直在研究如何为自定义 python 包构建文件夹结构。 There were several attempts, but none of them seemed to be applicable in general.
有几次尝试,但似乎没有一个是普遍适用的。 In particular, the usage (or not usage) of the
\\__init__.py
file(s).特别是
\\__init__.py
文件的使用(或不使用)。
I have a package that consists of several sub-packages, each being responsible to parse Files of a certain kind.我有一个由几个子包组成的包,每个包都负责解析某种类型的文件。 Therefore I currently adopted this structure:
因此,我目前采用了这种结构:
Parsers/
├── __init__.py
|
├── ExternalPackages
│ ├── __init__.py
│ ├── package1
│ └── package2
|
├── FileType1_Parsers/
│ ├── __init__.py
│ ├── parsers1.py
│ └── containers1.py
│
└── FileType2_Parsers/
├── __init__.py
├── parsers2.py
└── containers2.py
But it seems not very pythonic, that when I import his package and I want to use a certain class of a module I have to type something like但它似乎不是很pythonic,当我导入他的包并且我想使用某个模块的某个类时,我必须输入类似的东西
from Parsers.FileType1_Parsers.parsers1 import example_class
Is there any convention on how to structure such packages or any rules on how to avoid such long import lines?是否有关于如何构建此类包的约定或关于如何避免如此长的导入行的任何规则?
You can add the following line to Parsers/__init__.py
您可以
Parsers/__init__.py
添加到Parsers/__init__.py
from .FileType1_Parsers.parsers1 import example_class
Then you can import example_class
by然后你可以导入
example_class
from Parsers import example_class
This is a common practice in large package.这是大包装中的常见做法。
You can modify sys.path
at run-time so that it contains a directory for each module you'll be using.您可以在运行时修改
sys.path
以便它包含您将使用的每个模块的目录。 For example, for package1 issue the following statements:例如,对于 package1 发出以下语句:
>>> sys.path.append(r"[package directory path]\\Parsers\\FileType1_Parsers\\package1")
You can do this for any other modules in the package as well.您也可以对包中的任何其他模块执行此操作。 Now, you can just use this command:
现在,你可以使用这个命令:
from package1 import example_class
Hope this helps!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.