1

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?

2
  • Please preview your question before submitting it. It was quite unreadable. Commented Dec 8, 2010 at 12:41
  • 1
    cyclic import, read all about it. Commented Dec 8, 2010 at 12:43

2 Answers 2

4

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?

Sign up to request clarification or add additional context in comments.

1 Comment

No, not this either. Circular imports are valid in Python. What isn't valid is accessing attributes that don't exist.
2

The name doesn't exist in the module by the time you try to access it.

4 Comments

I don't think so. The error is not an AttributeError. It's an ImportError. The module couldn't be imported because of the cyclic dependency.
@Noufal: It's only an ImportError because the attribute is being specified in an import operation. Any non-existent name will give this.
Vazquez-Abram:If we pass parameters to functions and check whether to import or not,then will it work
@Rajeev: It will work if the attribute you're accessing exists at that time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.