简体   繁体   中英

How do I structure my Python package?

I have most of my code in project.py which requires a second file, 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.

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/
    __init__.py  # (renamed from project.py)
    otherfile.py

However I've read that __init__.py should be kept almost empty. 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:

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM