pythonsetuptoolsnamespace-package

List all sub-packages of a namespace package


Python has the ability to create a namespace packages. How do you get a list of installed packages under a namespace?

i.e. something like:

import namespace_package
dir(namespace_pageage)

Solution

  • From the Python Packaging User Guide:

    import pkgutil
    
    list(
        pkgutil.iter_modules(
            namespace_package.__path__,
            namespace_package.__name__ + "."
        )
    )
    

    Note that this will not return (sub-)namespace packages within the main namespace package (i.e. if you have nested namespace packages).