Control module imports

gui commited 7 years ago · 🐍 Python

Let's imagine following structure

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

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

Importing name

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

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

Now we can access this way:

main.py

from A import ClassA
main.py

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"]
__init__.py

main.py

from A import CustomA
main.py
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket