tags:

views:

46

answers:

2

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?

+2  A: 

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 beem 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.

katrielalex
thanks, if i do a from src import *, does it only take globals from the __init__ file? or will it take globals from other modules within src\ ?
biokiwi
It's documented below. If you have defined `__all__` in `__init__.py`, it will take all of those. If you haven't, it will take only those that are explicitly imported. But this is a workaround for those people that use `import *`; you shouldn't do that.
katrielalex
A: 

you should define all as specified in

http://docs.python.org/tutorial/modules.html#importing-from-a-package

damir