ImportError: Cannot import name X

前端 未结 16 1205
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 04:33

I have four different files named: main, vector, entity and physics. I will not post all the code, just the imports, because I think that\'s where the error is. (If you want

16条回答
  •  别跟我提以往
    2020-11-22 04:52

    To make logic clear is very important. This problem appear, because the reference become a dead loop.

    If you don't want to change the logic, you can put the some import statement which caused ImportError to the other position of file, for example the end.

    a.py

    from test.b import b2
    
    def a1():
        print('a1')
        b2()
    

    b.py

    from test.a import a1
    
    def b1():
        print('b1')
        a1()
    
    def b2():
        print('b2')
    
    if __name__ == '__main__':
        b1()
    

    You will get Import Error: ImportError: cannot import name 'a1'

    But if we change the position of from test.b import b2 in A like below:

    a.py

    def a1():
        print('a1')
        b2()
    
    from test.b import b2
    

    And the we can get what we want:

    b1
    a1
    b2
    

提交回复
热议问题