ImportError: Cannot import name X

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

    In my case, I was working in a Jupyter notebook and this was happening due the import already being cached from when I had defined the class/function inside my working file.

    I restarted my Jupyter kernel and the error disappeared.

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

    If you are importing file1.py from file2.py and used this:

    if __name__ == '__main__':
        # etc
    

    Variables below that in file1.py cannot be imported to file2.py because __name__ does not equal __main__!

    If you want to import something from file1.py to file2.py, you need to use this in file1.py:

    if __name__ == 'file1':
        # etc
    

    In case of doubt, make an assert statement to determine if __name__=='__main__'

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

    This is a circular dependency. It can be solved without any structural modifications to the code. The problem occurs because in vector you demand that entity be made available for use immediately, and vice versa. The reason for this problem is that you asking to access the contents of the module before it is ready -- by using from x import y. This is essentially the same as

    import x
    y = x.y
    del x
    

    Python is able to detect circular dependencies and prevent the infinite loop of imports. Essentially all that happens is that an empty placeholder is created for the module (ie. it has no content). Once the circularly dependent modules are compiled it updates the imported module. This is works something like this.

    a = module() # import a
    
    # rest of module
    
    a.update_contents(real_a)
    

    For python to be able to work with circular dependencies you must use import x style only.

    import x
    class cls:
        def __init__(self):
            self.y = x.y
    

    Since you are no longer referring to the contents of the module at the top level, python can compile the module without actually having to access the contents of the circular dependency. By top level I mean lines that will be executed during compilation as opposed to the contents of functions (eg. y = x.y). Static or class variables accessing the module contents will also cause problems.

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

    Don't name your current python script with the name of some other module you import

    Solution: rename your working python script

    Example:

    1. you are working in medicaltorch.py
    2. in that script, you have: from medicaltorch import datasets as mt_datasets where medicaltorch is supposed to be an installed module

    This will fail with the ImportError. Just rename your working python script in 1.

    0 讨论(0)
提交回复
热议问题