开发者

Import error in python

开发者 https://www.devze.com 2023-01-29 05:40 出处:网络
In file1.py: def test1(): print \"hi\" In file2.py: from file1 import test1 def test2(): print \"hello\" test1()

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?


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?


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

0

精彩评论

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

关注公众号