ImportError: cannot resolve import name

As a result of writing unorganized code, I got an error.

error contents

Traceback (most recent call last):
  File "code1.py", line 7, in <module>
    from code2 import my_function1
  File "/home/ubuntu/code2.py", line 9, in <module>
    import code3
  File "/home/ubuntu/code3.py", line 6, in <module>
    from code1 import my_function2
  File "/home/ubuntu/code1.py", line 7, in <module>
    from code2 import my_function1
ImportError: cannot import name 'my_function1'

Cause

The import is in an infinite loop.

スクリーンショット 2020-01-08 12.13.46.png

Solution

Make it a local import instead of a global import.

Original code

code1.py


from code2 import my_function1
def main():
    my_function1()

Corrected code

code1.py



def main():
    from code2 import my_function1
    my_function1()

This seems to be a symptomatic treatment, so I think it is basically better to clarify the master-slave relationship of imports.

Related article

ImportError: cannot resolve import name

Recommended Posts

ImportError: cannot resolve import name
ImportError: cannot resolve import name
ImportError: cannot import name'factorial' ~ ~ ~
from scipy.misc If "ImportError: cannot import name imread" occurs in import imread, imresize
Cannot import name'NUMPY_MKL'Solution.
ImportError: cannot import name'factorial' ~ ~ ~
ImportError: cannot resolve import name
ImportError: cannot resolve import name
Cannot import name'NUMPY_MKL'Solution.
from scipy.misc If "ImportError: cannot import name imread" occurs in import imread, imresize
When it becomes Cannot import name "Feature" from "setuptools".
What to do when "cannot import name xxx" [Python]
Resolve VS Code unresolved import error
If you are told cannot by Python import, review the file name