Home > Blockchain >  Python - "ImportError: cannot import name" for modules in the same directory
Python - "ImportError: cannot import name" for modules in the same directory

Time:07-10

I have two python files in the same directory. I have also __init__.py file as well. Python version is: 3.9.7

Can't figure out why I can't import the modules.

a.py

def aaa():
    print ("test")

b.py

from a import aaa

aaa()

Error:

from a import aaa
ImportError: cannot import name 'aaa' from 'a' (/usr/lib64/python3.9/a.py)

Also it doesn't work:

from .a import aaa

ImportError: attempted relative import with no known parent package

Running it as: python b.py I have tried other options but without success.

Update: The same simple code from a import aaa aaa() without init.py works on python 2.7.

OS: 
"Red Hat Enterprise Linux 8.5"

Thanks!

CodePudding user response:

For relative imports in the same folder, use a single .

from .a import aaa

CodePudding user response:

Like Samathingamajig pointed out, you need relative imports.

So, first, change the line in b.py to:

from .a import aaa

You also need to deal with the fact that you now have a package instead of a single module. And Python needs to know how to find your modules.

One way tot deal with that, is to run it using -m. If your Python files are in /some/dir/myproject/, run it as follows:

cd /some/dir
python3 -m myproject.b

Note the namespace dot replacing the directory separator in that last command.

Alternatively, install your package (I recommend learning about packaging but for now you can simply move the myproject directory into one of the directories in sys.path), and then you could have any Python file import myproject.b or run python3 -m myproject.b from any directory.

If you want to have a package that can be used both as a library and a stand-alone application, you could add a __main__.py file with the code to run it as an application. That way python3 -m myproject would run your main project

  • Related