Search code examples
pythonmodulepackagesetuptools

Cannot load classes from installed module


I am developing a project with Python 3 and I would like to pack it as a Python module so it can be installed as a library to our machines. However I am having a problem with importing the module after installation so let me show you the code

├── README.txt
├── setup.py
├── virt_template
│   ├── debian
│   │   └── interfaces
│   ├── debian_platform.py
│   ├── __init__.py
│   ├── virt_template.py
│   └── test
│       ├── __init__.py
│       └── virt_template_test.py

This is the setup.py content

from setuptools import setup, find_packages

setup(
    name = "virt_template",
    packages = find_packages(),
    package_data = {"virt_template" : ["debian/*"]},
    version = "1.0.0",
    author = "Petr Mensik",
    author_email = "[email protected]",
    classifiers = [
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Intended Audience :: Developers",
        "Operating System :: Linux",
        "Topic :: Software Development :: Libraries :: Python Modules",
    ]
)

Now when I run python3 setup.py install the module is correctly installed into /usr/local/lib/python3.4/dist-packages/virt_template-1.0.0-py3.4.egg/virt_template with folder structure like this

├── debian
│   └── interfaces
├── debian_platform.py
├── __init__.py
├── virt_template.py
└── test
    ├── __init__.py
    └── virt_template_test.py

So far so good, that seems correct to me. However when I do

from virt_template import VirtualMachine 

I get cannot import name VirtualMachine. So I tried

from virt_template.virt_template import VirtualMachine 

and the result is No module named 'debian_platform' - which is probably referring to debian_platform.py file.

So what am I doing wrong?


Solution

  • In you case the correct import is

    from virt_template.virt_template import VirtualMachine 
    

    Your problem is the way you import relative modules from virt_template.py. You should either do

    from . import debian_platform
    

    or

    from virt_template import debian_platform
    

    The root cause of your trouble is the pythonpath which is set to inside the virt_template directory when you are testing the code, and to a site_packages library dir when used after installation with setuptools