简体   繁体   English

如何构建我的Python包?

[英]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.

相关问题 如何使用 Python 'unittest' 模块构建我的测试? - How do I structure my tests with the Python 'unittest' module? 如何为我的 PyCharm Python 项目安装 yaml 包? - How do I install the yaml package for my PyCharm Python project? 如何使用我的python包分发字体? - How do I distribute fonts with my python package? Python:如何在软件包或存储库中安装软件包? - Python: How do I install packages within my package or repository? 批判我的Python包结构 - Critique my Python Package Structure 如何导入和使用我的 python package? - How do I import and use my python package? Python包内导入-如何获得在包中散布的通用函数/类? - Python Intra-Package Imports - How do I get common functions/classes spread throughout my package? 如何将未更改的C扩展打包为新Python打包的一部分? - How do I package an unchanged C extension as part of my new Python package? 如何使用我的 Python3 fbs package package 一个 Sqlite3 数据库? - How do I package an Sqlite3 database with my Python3 fbs package? 我如何用大量文件构建我的 Python 子模块,以便我只需要导入一个模块 - How do i structure my Python submodule with a lot of files, so that i have to import only one module
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM