ModuleNotFoundError when using setup.py install version of package, but not locally-

Problem


python setup.py install installs a package I’m developing all fine, but when I try importing the package I get a "ModuleNotFoundError" saying that a local package could not be found. The package works when locally (when I cd to the directory and attempt importing it in the python interpreter from there).

Recreation:


C:.
│   setup.py
│
└───package
    │   __init__.py
    │
    └───networking
            hello.py
            __init__.py

setup.py

from setuptools import setup

setup(
    name="test_package",
    packages=["package"],
    version="0.0.1",
    description="Test",
)

package/networking/__init__.py

from package.networking.hello import Hello

package/networking/hello.py

class Hello:
    def __init__(self, name):
        self.name = name

    def hello(self):
        print("Hello", self.name)

The following code works when testing locally (meaning, you cd to the directory with the package, then enter python interpreter there and try), but not after I have installed the package with setup.py install:

> python setup.py install
> cd .. # Change directory so we don't import locally, but use the version installed with setup.py
> python
>>> from package.networking import Hello
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'package.networking'
>>> 

In constrast, this works when I’m in the same directory as the package:

> python
>>> from package.networking import Hello
>>> Hello("Test").hello()
Hello Test

>Solution :

setup(
    name="test_package",
    packages=["package"],
    ...
)

Don’t you miss something?

packages=[
    'package',
    'package.networking'
],
package_dir={
    'package': 'package',
    'package.networking': 'package/networking',
},

This is an example: first list all the packages, and then associate them with the directories.


setup.py must know which modules are to build, which name to give them, and where to find them.

Leave a Reply