ImportError: cannot import name (unknown location)

Viewed 16298

The project structure

my_package
├── my_package
│   ├── __init__.py
│   └── my_module.py
└── setup.py

The module my_module.py has a single func function I am attempting to import.

The setup.py file has the following content.

from setuptools import setup, find_packages

setup(
    name='my_package',
    packages=find_packages(where='my_package'),
    version='1.0'
)

The import API

I'm installing the package with:

virtualenv --python=/usr/bin/python3.8 venv
source venv/bin/activate
python my_package/setup.py install

To then import it with:

import my_package
from my_package import my_module

However, the second import fails with:

ImportError: cannot import name 'my_module' from 'my_package' (unknown location)

Further more, running dir(my_package) reveals that indeed the my_module name did not get imported. ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']

Similar questions on SO

setup.py installed package can't be imported provided solution proved non sucessfull.

ImportError: cannot import name 'Serial' from 'serial' (unknown location) adding a __init__.py file in my_package/my_package didn't work.

Git repo

I've placed an example of the issue at GitLab

1 Answers

You're running your test.py script in the parent directory of your my_package directory. As a result, test.py will try and import the my_package subdirectory as a package/module, not your installed package. You will need to move to a directory that doesn't contain your source code and then run test. This could be as simply as running it inside a subdirectory test in the my_package main directory.
Just make sure you cd into that directory explicitly, instead of running it with a full path (like, for example, python3.8 my_package/test/test.py, because then it will still import the wrong my_package.

The reason for this (and cause of your problem) is that Python automatically includes the current working directory in your sys.path, at the start, and will thus try and import the main my_package directory as a package.

Related