4
votes

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
To be clear, did you try also adding a __init__.py in my_package/my_package? Perhaps with contents import .my_module? - Green Cloak Guy
@GreenCloakGuy Yes. I've updated the last phrase in th question. The __init__.py was placed in my_package/my_package. Adding the import you just said, didnt' work either. - Pedro Rodrigues
From which (directory) location do you run the script (or Python prompt) that uses from my_package import my_module? - 9769953
@00 check gitlab.com/prodrigues1990/import-setup/-/jobs/718813294 see if it answers your question - Pedro Rodrigues
You can also look in venv/lib/python3.8/site-packages/my_package to see if my_module.py is there. - 9769953

1 Answers

3
votes

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.