Search code examples
pythonpackageinitpython-packagingmodulenotfounderror

Cannot import from my custom python package. ModuleNotFoundError: No module named 'a_python_file_inside_my_custom_module'


I am trying to build a python package following this tutorial.

So I have made a base folder, then a module folder, then inside it I have placed the file starting_template.py, which contains the function load_img and a __init__.py file whose content is barely

from starting_template import load_img
print("loaded!")

If I manually run __init__.py, it works without showing any error, it prints "loaded!".

So this is the directory tree:

enter image description here

I have built the package by running

python setup.py sdist bdist_wheel

in the base directory, then I have uploaded the package on my pypi account by running

twine upload dist/opencv_auxiliary_for_vscode-0.0.2*

where 0.0.2 is the version number of the distribution,
and finally installed the module by running

pip install opencv_auxiliary_for_vscode==0.0.2

The package is uploaded here.
It is a lame code, but it is just to practice the process of building python packages.

Then, in a python file, I wrote the import statement

from opencv_auxiliary_for_vscode import load_img

but as I run it, I get the error

ModuleNotFoundError: No module named 'starting_template'

I have also tried to import

from opencv_auxiliary_for_vscode.starting_template import load_img

but it does not work.

What am I possibly doing wrong?


Solution

  • As indicated by @h4z3, I had to change the content of __init__.py from

    from starting_template import load_img
    print("loaded!")
    

    to

    from .starting_template import load_img  # with the dot
    print("loaded!")
    

    to show it is a local import.

    When you don't have the dot, it tries to find starting_template in standard and installed packages.

    It ( running __init__.py ) worked before because you run the code as code, not as module, and current directory is always added to PATH

    Also I had to increment by 0.0.1 the VERSION variable in setup.py every time I made a new attempt to re-upload the module

    python setup.py sdist bdist_wheel
    
    twine upload dist/opencv_auxiliary_for_vscode-0.0.3*
    # __token__
    # PyPI api key
    
    pip install opencv_auxiliary_for_vscode==0.0.3