I have some problem, that look like some spaces in my understanding how python does import modules. For example i have module which called somemodule with two submodules a.py and b.py.
content of a.py:
from somemodule.b import b
def a():
b()
print "I'am A"
content b.py
from somemodule.a import a
def b():
a()
print "I'am B"
Now if i would like to invoke any module i get
ImportError:
ImportError: cannot import name b
Whats wrong with me?
-
What's your file layout? Why are you importing somemodule if a.py and b.py are side by side?richardolsson– richardolsson2011年08月26日 13:44:08 +00:00Commented Aug 26, 2011 at 13:44
-
2some reading: How can I have modules that mutually import each other?Jeannot– Jeannot2011年08月26日 13:57:40 +00:00Commented Aug 26, 2011 at 13:57
2 Answers 2
You've got a circular reference. You import module a which then imports module b. But module b imports function a from module a. But at the time it tries to do so, a has not been defined. Remember that Python import effectively executes the module.
The solution would appear to be to move the function definitions so that they appear before the imports.
Or, as @lazyr suggests, move the import statements to be inside the functions so that the import happens when the function is called, not at module import time.
2 Comments
You have recursive importing here: a imports b which imports a which imports b which .....
In addition, please make sure you have an __init__.py file in the folder somemodule