In file1.py:
def test1():
print "hi"
In file2.py:
from file1 import test1
def test2():
print "hello"
test1()
test2()
Output:
hi
hello
Now in file 1 if i include test2 i get the following error:
from file2 import test2
def test1():
print "hi"
Traceback (most recent call last):
File "file1.py", line 1, in ?
from file2 import test2
File "/root/pyt/file2.py", line 1, in ?
from file1 import test1
File "/root/pyt/file1.py", line 1, in ?
from file2 import test2
ImportError: cannot import name test2
Can some explain why and how to make it work?
-
Please preview your question before submitting it. It was quite unreadable.Noufal Ibrahim– Noufal Ibrahim2010年12月08日 12:41:54 +00:00Commented Dec 8, 2010 at 12:41
-
1cyclic import, read all about it.SilentGhost– SilentGhost2010年12月08日 12:43:14 +00:00Commented Dec 8, 2010 at 12:43
2 Answers 2
This is a circular import problem. You are importing file2 from file1 and then at the top level of file2, importing file1 again. This means that 1 cannot load unless you import 2 and 2 cannot load unless you import `1.
As for how to make it work, can you explain what you want to do? Why don't you just put both these functions in the same module and import that in a single go?
1 Comment
The name doesn't exist in the module by the time you try to access it.
4 Comments
AttributeError. It's an ImportError. The module couldn't be imported because of the cyclic dependency.ImportError because the attribute is being specified in an import operation. Any non-existent name will give this.