Search code examples
pythonpython-3.ximport

Python 3 - ImportError: cannot import name


I have a folder:

python_scripts/test_import/
|-- __init__.py
|-- m1.py
`-- m2.py

Content of m1.py:

a=3

Content of m2.py:

from . import m1

print(m1.a)

When I try to execute m2.py, I get the following error:

# python3 python_scripts/test_import/m2.py
Traceback (most recent call last):
  File "python_scripts/test_import/m2.py", line 1, in <module>
    from . import m1
ImportError: cannot import name 'm1'

But if I change import in m2.py to this:

import m1

print(m1.a)

then I see no errors and result of execution is expected:

3

Question: Why relative import with dot doesn't work here?


Solution

  • Error: can't import name m1 Relative import uses the __name__ attribute of the imported file to determine the location of the file in the entire package structure, but when the python script is run directly, the __name__ of the module is set to __main__ instead of the original name of the module. In this way, the relative path cannot be recognized. So for this you can't just directly using that, your main.py need to be on the top files

    python_scripts/     
      |-- main.py :from test_import.m import m2
        /test_import/
          _init_.py
          /m/
            |-- __init__.py
            |-- m1.py
            |-- m2.py
    

    Or if you insist to do so, you have to change into from .m1 import *