What i want to is, I have foo.py it imports classes from bar1, bar2, and they both need bar3, e.g.
foo.py
from src import *
...
src/ __ init__.py
from bar1 import specialSandwichMaker
from bar2 import specialMuffinMaker
src/bar1.py
import bar3
class specialSandwichMaker(bar3.sandwichMaker)
...
src/bar2.py
import bar3
class specialMuffinMaker(bar3.muffinMaker)
...
is there a more efficient way to make bar3 available to the bar1 and bar2 files without having them directly import it?
This is fully efficient; when importing a module Python will add it to sys.modules
. import
statements first check this dictionary (which is fast because dictionary lookups are fast) to see whether the module has been imported already. So in this case, bar1
will import bar3
and add it to sys.modules
. Then bar2
will use the bar3
that has already been imported.
You can verify this with:
import sys
print( sys.modules )
Note that from src import *
is bad code and you shouldn't use it. Either import src
and use src.specialSandwichMaker
references, or from src import specialSandwichMaker
. This is because modules shouldn't pollute each other's namespaces -- if you do from src import *
, all the global variables defined in src
will appear in your namespace too. This is Bad.
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