Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Finding all packages inside a package

Given a package, how can I automatically find all its sub-packages?

like image 798
Ram Rachum Avatar asked May 06 '09 22:05

Ram Rachum


1 Answers

You can't rely on introspection of loaded modules, because sub-packages may not have been loaded. You'll have to look at the filesystem, assuming the top level package in question is not an egg, zip file, extension module, or loaded from memory.

def get_subpackages(module):
    dir = os.path.dirname(module.__file__)
    def is_package(d):
        d = os.path.join(dir, d)
        return os.path.isdir(d) and glob.glob(os.path.join(d, '__init__.py*'))

    return filter(is_package, os.listdir(dir))
like image 108
James Emerton Avatar answered Sep 30 '22 00:09

James Emerton