Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python module structure for classes

I'm currently working on a project that I am structuring in the following manner:

.
├── example_app
│   ├── __init__.py
│   ├── app.py
│   ├── requirements.txt
│   └── classes
│       ├── ExampleClass1.py
│       ├── ExampleClass2.py
│       ├── __init__.py
└── tests
    └── test_app.py

Inside of classes/__init__.py I have defined a base class for all of the other "ExampleClasses" to inherit from. Then, inside of app.py I need to import all of these classes. However, this becomes very verbose, as I have to type:

from example_app.classes.ExampleClass1 import ExampleClass1
from example_app.classes.ExampleClass2 import ExampleClass2
...

Is there a way to structure this in a better way? Ideally I would like to keep each class in a separate file as they are not really similar to each other. I thought of importing all the classes inside of classes/__init.py but that does not seem right.

Note that although I only pictured 2 example classes there could be several (tens) of them so importing by hand is quite cumbersome and brittle.

like image 711
srb Avatar asked Mar 23 '26 16:03

srb


1 Answers

In my opinion, importing all the classes you want to expose from the subpackage classes inside its __init__.py is the way to go. In fact, that's what many top-tier Python libraries/frameworks do (see TensorFlow/Keras layers subpackage here and Python's multiprocessing subpackage here).

When doing that, however, you should probably follow Google Python Style Guide and:

Use import statements for packages and modules only, not for individual classes or functions. Note that there is an explicit exemption for imports from the typing module.

In your case, it would translate to this:

example_app/classes/__init__.py:

from example_app.classes.ExampleClass1 import ExampleClass1
from example_app.classes.ExampleClass2 import ExampleClass2

example_app/__init__.py:

# ...
from example_app import classes
# ...

Some other .py:

from example_app import classes
ex1_instance = classes.ExampleClass1()

Or even better:

import example_app as ex
ex1_instance = ex.classes.ExampleClass1()
like image 186
Talendar Avatar answered Mar 26 '26 04:03

Talendar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!