Control module imports

Quickly reference of how to use __init__.py to import ...

latrova commited 1 year, 9 months ago
Control - Read as you want

Let's imagine following structure

project/
|_ main.py
|_ A
|  |_ __init__.py
|  |_ ClassA.py
|
|_ B
   |_ __init.__.py
   |_ ClassB.py

Empty __init__.py

This way, if you need to use both classes in __main__.py , you will need to import like this:

from A.ClassA import ClassA
from B.ClassB import ClassB

Importing name

Which can get redundant, so in A __init__.py we will do the following:

from .ClassA import ClassA
__all__ = ["ClassA"]

Now we can access this way:

main.py

from A import ClassA
Simple and direct to the point, you can repeat same for ClassB in its respective __init__.py

Customizing imported name

Note that __all__ should always be a list of strings with names that you've imported. If I would want to change imported name, I could:

__init.py__

from .ClassA import ClassA as CustomA
__all__ = ["CustomA"]

main.py

from A import CustomA
blog comments powered by Disqus