Suppose I have the following structure:
app/
__init__.py
foo/
a.py
b.py
c.py
__init__.py
a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the __init__.py
file so I don't have to import them in every one of the files?
Edit: My goal is to avoid having to import 5-6 modules in each file and it's not related to performance reasons.
You can do this using a common file such as include.py
, but it goes against recommended practices because it involves a wildcard import. Consider the following files:
app/
__init__.py
foo/
a.py
b.py
c.py
include.py <- put the includes here.
__init__.py
Now, in a.py
, etc., do:
from include import *
As stated above, it's not recommended because wildcard-imports are discouraged.
No, they have to be put in each module's namespace, so you have to import them somehow (unless you pass logging
around as a function argument, which would be a weird way to do things, to say the least).
But the modules are only imported once anyway (and then put into the a
, b
, and c
namespaces), so don't worry about using too much memory or something like that.
You can of course put them into a separate module and import that into each a
, b
, and c
, but this separate module would still have to be imported everytime.
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