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.importstatements 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,bar1will importbar3and add it tosys.modules. Thenbar2will use thebar3that has already been imported.You can verify this with:
Note that
from src import *is bad code and you shouldn’t use it. Eitherimport srcand usesrc.specialSandwichMakerreferences, orfrom src import specialSandwichMaker. This is because modules shouldn’t pollute each other’s namespaces — if you dofrom src import *, all the global variables defined insrcwill appear in your namespace too. This is Bad.