Search code examples
pythonimportpackagerelative-pathpypi

ModuleNotFoundError while creating minimal python package


I made a very simple python package by following the packaging guide:

tester
├── A.py
├── B.py
└── __init__.py

The contents of A.py are simply:

import B

__init__.py and B.py are empty files.

I uploaded the package to testpypi and installed it in a virtual environment. I started first by checking if it works by making a simple test.py file:

from tester import A

Then I try to run that file:

(scratch-venv) [ccn@sy337b4 scratch-box]$ python test.py
Traceback (most recent call last):
  File "/home/ccn/scratch-box/test.py", line 1, in <module>
    from tester import A
  File "/home/ccn/scratch-box/scratch-venv/lib/python3.9/site-packages/tester/A.py", line 1, in <module>
    import B
ModuleNotFoundError: No module named 'B'

I'm confused because when I was developing the package running python A.py never caused an error, but now when I'm importing A it doesn't work any more.

(within the venv, aka: client using package) I was able to fix this by changing the contents of A.py to :

from tester import B

But that's not a solution because when I go back to developing the package I get this error when running python A.py

Traceback (most recent call last):
  File "/home/ccn/tester_package/src/tester/A.py", line 1, in <module>
    from tester import B
ModuleNotFoundError: No module named 'tester'

Finally for full context I will post the structure of the package. I am developing in src/tester

.
├── build
│   ├── bdist.linux-x86_64
│   └── lib
│       └── tester
│           ├── A.py
│           ├── B.py
│           └── __init__.py
├── dist
│   ├── example_pkg_2_cuppajoeman-0.0.1-py3-none-any.whl
│   └── example-pkg-2-cuppajoeman-0.0.1.tar.gz
├── LICENSE
├── pyproject.toml
├── README.md
├── setup.cfg
└── src
    ├── example_pkg_2_cuppajoeman.egg-info
    │   ├── dependency_links.txt
    │   ├── PKG-INFO
    │   ├── SOURCES.txt
    │   └── top_level.txt
    └── tester
        ├── A.py
        ├── B.py
        ├── __init__.py
        └── __pycache__
            └── B.cpython-39.pyc

9 directories, 17 files

Solution

  • If I remember correctly, in tester/a.py you should have either one of those:

    from . import B
    
    from tester import B
    
    import tester.B