I have a question about importing modules inside a python package. I do not know how to do it such that I can run the python code, and also import the package somewhere else.
Setup
Here is the minimal example's folder structure
.
├── test_package/
│ ├── __init__.py
│ ├── module_A.py
│ └── module_B.py
│
├── LICENCE
├── README.md
└── setup.py
The files contain
_init_.py
from .module_A import *
from .module_B import *
module_A.py
from module_B import c
def print_variable():
print(c)
if __name__ == "__main__":
print_variable()
module_B.py
c = 5
setup.py
import setuptools
setuptools.setup(
name="test_package",
version="0.0.1",
author="Example Author",
author_email="author@example.com",
description="A small example package",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
)
The problem
If I simply run
python test_package/module_A.py
I get the expected output of 5
. So far, so good.
Now I want to install the package (e.g. to run unit tests on it from a separate folder). I do this via
pip install .
from the root folder. The installation works fine, but if I now try to import the package, I find
python
Python 3.7.3 (default, Mar 27 2019, 16:54:48)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import test_package
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/path/to/package/test_package/__init__.py", line 1, in <module>
from .module_A import *
File "/path/to/package/test_package/test_package/module_A.py", line 1, in <module>
from module_B import c
ModuleNotFoundError: No module named 'module_B'
>>>
When importing module_A
, it seems to be unable to locate module_B
.
What I tried to fix it
I can adjust the import line in module_A.py
by adding a dot .
to
from .module_B import c
# ...
Then I can import the package and use its function.
python
Python 3.7.3 (default, Mar 27 2019, 16:54:48)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import test_package
>>> test_package.print_variable()
5
However, I can no longer run the script.
python test_package/module_A.py
Traceback (most recent call last):
File "test_package/module_A.py", line 1, in <module>
from .module_B import c
ModuleNotFoundError: No module named '__main__.module_B'; '__main__' is not a package
Now the script can not find module_B
anymore.
So, if I use a relative import and include the .
, the package import works well, but the script no longer finds the module. On the other hand, without the .
, I can run the script, but not import the package after installation. What am I doing wrong?