tompreston
tompreston

Reputation: 690

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

Upvotes: 1

Views: 113

Answers (1)

Amber
Amber

Reputation: 526483

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.

Upvotes: 2

Related Questions