Search code examples
pythonpipsetuptoolspython-modulepypi

I cannot import a Python package despite it being on the right path


I wrote a Python package and uploaded it to PyPI (note: I have been working on Python 3.11.3 and set Python >=3.11 as a requirement to make sure the package is compatible).

Subsequently, I installed it via pip by executing pip install graphab4py. However, I could not import it in a Python script (which is not the case with other packages I installed via pip.) To be sure, I set up a virtual environment and installed the package there. Within the virtual environment, I started a Python session and tried to import the package, again with no success.

I stumbled upon some suggestions on how to list available packages and I tried the following in Python in my virtual environment:

for dist in __import__('pkg_resources').working_set:
    print(dist.project_name.replace('Python', ''))

output:

setuptools
pip
graphab4py

It clearly lists the package there. So I tried import graphab4py again, and, once more, I got

ModuleNotFoundError: No module named 'graphab4py'

So I suspect there might be something wrong with my package? Does anybody have a clue what the issue might be?

Edit

I found some hint that there might be some issue with the installation: Where my packages are located, there is a folder graphab4py-1.0.1.dist-info but no folder named graphab4py. There was no error during the installation, though. The package code can also be viewed on GitHub


Solution

  • Thanks to @tdelaney and a lot of web pages, I made it work. First of all, an __init__.py file was missing. The other issue was that the package is located within ./src and it was necessary to point that out. So I added in setup.py:

    setup(
          ...
          package_dir = {"": "src"},
          packages = find_packages("./src"),
          ...
    )
    

    and in pyproj.toml:

    [tool.setuptools]
    package-dir = {"" = "src"}
    
    [tool.setuptools.packages.find]
    where = ["src"]
    include = ["*"]
    namespaces = false
    

    of which I believe some must be superfluous, but at least I can now install and import the package. Feel free to point out what changes coule have been done better/more efficiently.