开发者

Python importing modules that all import another module that is the same

开发者 https://www.devze.com 2023-01-11 05:51 出处:网络
What i want to is, I have foo.py it imports classes from bar1, bar2, and they both need bar3, e.g. foo.py

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 file开发者_开发技巧s 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.


you should define all as specified in

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

0

精彩评论

暂无评论...
验证码 换一张
取 消