ImportError: Cannot import name X

前端 未结 16 1176
隐瞒了意图╮
隐瞒了意图╮ 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:57

    I just got this error too, for a different reason...

    from my_sub_module import my_function
    

    The main script had Windows line endings. my_sub_module had UNIX line endings. Changing them to be the same fixed the problem. They also need to have the same character encoding.

    0 讨论(0)
  • 2020-11-22 04:59

    While you should definitely avoid circular dependencies, you can defer imports in python.

    for example:

    import SomeModule
    
    def someFunction(arg):
        from some.dependency import DependentClass
    

    this ( at least in some instances ) will circumvent the error.

    0 讨论(0)
  • 2020-11-22 05:00

    You have circular dependent imports. physics.py is imported from entity before class Ent is defined and physics tries to import entity that is already initializing. Remove the dependency to physics from entity module.

    0 讨论(0)
  • 2020-11-22 05:02

    One way to track import error is step by step trying to run python on each of imported files to track down bad one.

    1. you get something like:

      python ./main.py
      

      ImportError: cannot import name A

    2. then you launch:

      python ./modules/a.py
      

      ImportError: cannot import name B

    3. then you launch:

      python ./modules/b.py
      

      ImportError: cannot import name C (some NON-Existing module or some other error)

    0 讨论(0)
  • 2020-11-22 05:02

    In my case, simply missed filename:

    from A.B.C import func_a (x)

    from A.B.C.D import func_a (O)

    where D is file.

    0 讨论(0)
  • 2020-11-22 05:10

    This is a circular dependency. we can solve this problem by using import module or class or function where we needed. if we use this approach, we can fix circular dependency

    A.py

    from B import b2
    def a1():
        print('a1')
        b2()
    

    B.py

    def b1():
       from A import a1
       print('b1')
       a1()
    
    def b2():
       print('b2')
    if __name__ == '__main__':
       b1() 
    
    0 讨论(0)
提交回复
热议问题