Search code examples
pythondistutilssetup.py

make distutils in Python automatically find packages


When describing a python package in setup.py in distutils in Python, is there a way to make it so automatically get every directory that has a __init__.py in it and include that as a subpackage?

ie if the structure is:

mypackage/__init__.py
mypackage/a/__init__.py
mypackage/b/__init__.py

I want to avoid doing:

packages = ['mypackage', 'mypackage.a', 'mypackage.b']

and instead just do:

packages = ['mypackage']

and have it automatically find things like a and b since they have an init file. thanks.


Solution

  • The easiest way (that I know of) is to use pkgutil.walk_packages to yield the packages:

    from distutils.core import setup
    from pkgutil import walk_packages
    
    import mypackage
    
    def find_packages(path=__path__, prefix=""):
        yield prefix
        prefix = prefix + "."
        for _, name, ispkg in walk_packages(path, prefix):
            if ispkg:
                yield name
    
    setup(
        # ... snip ...
        packages = list(find_packages(mypackage.__path__, mypackage.__name__)),
        # ... snip ...
    )