Right way to set python package with sub-packages

Dror picture Dror · Oct 23, 2014 · Viewed 14.3k times · Source

I am trying to set a package with sub-packages in python. Here is the tree structure that I have at the moment:

myPackage
├── __init__.py
├── mySubPackage1
│   ├── foo2.py
│   ├── foo.py
│   └── __init__.py
├── mySubPackage2
│   ├── bar2.py
│   ├── bar.py
│   └── __init__.py
└── setup.py

All __init__.py are empty. Here is my setup.py:

from distutils.core import setup

if __name__ == "__main__":
    setup(
        name='myPackage',
        package_dir = {
            'mySubPackage1': 'mySubPackage1',
            'mySubPackage2': 'mySubPackage2'},
        packages=['mySubPackage1', 'mySubPackage2'],
    )

The problem is that, when I run python setup.py install from myPackage, the sub packages are installed into dist-packages:

/usr/local/lib/python2.7/dist-packages/mySubPackage1
/usr/local/lib/python2.7/dist-packages/mySubPackage2

I guess the problem is my setup.py, but I don't know how to fix it? Should it be in the parent directory of myPackage? If so, then how does it work when I pack the package into a zip using python setup.py sdist?

Answer

Max Malysh picture Max Malysh · May 5, 2017

Just use setuptools instead of distutils, it has find_packages exactly for that purpose:

from setuptools import setup, find_packages

setup(
    name='myPackage',
    packages=find_packages(),
)