Say i have this this structure.
MyApp
├── main.py
└── package
├── __init__.py
├── a.py
├── b.py
├── c.py
├── d.py
├── e.py
├── f.py
├── g.py
├── h.py
├── ...
└── z.py
And in main.py
I need to use all modules, from a.py
to z.py
I'd like to know how I can import all those modules with one import statement.
So instead of doing
from package import a
from package import b
...
from package import z
I could just import the package and have all the modules ready.
Things I've tried
import package
a = package.a.A()
# AttributeError: 'module' object has no attribute 'a'
Now I know I could put a code in __init__.py
to add all the modules to __all__
, but from what I've read, we should avoid 'from package import *'
The reason for this is that the package might have an increasing number of modules and I would like to adding an import statement to the main code each time a module is created. Ideally I'd like to be able to just drop the module in the package and have it ready for use.
In __init__.py
, you can:
import a, b, c, d...
and then the modules will be placed in the package
namespace after you do import package
.
You you really want to names a
, b
, etc. in main.py's namespace, and have this happen with no effort, you can't really avoid from package import *
; any other method of importing them all implicitly is going to be just as bad, since it involves polluting the namespace with names you don't explicitly import.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With