pythonmodulepackageintrospectionpython-import

List all the modules that are part of a python package?


Is there a straightforward way to find all the modules that are part of a python package? I've found this old discussion, which is not really conclusive, but I'd love to have a definite answer before I roll out my own solution based on os.listdir().


Solution

  • Yes, you want something based on pkgutil or similar -- this way you can treat all packages alike regardless if they are in eggs or zips or so (where os.listdir won't help).

    import pkgutil
    
    # this is the package we are inspecting -- for example 'email' from stdlib
    import email
    
    package = email
    for importer, modname, ispkg in pkgutil.iter_modules(package.__path__):
        print "Found submodule %s (is a package: %s)" % (modname, ispkg)
    

    How to import them too? You can just use __import__ as normal:

    import pkgutil
    
    # this is the package we are inspecting -- for example 'email' from stdlib
    import email
    
    package = email
    prefix = package.__name__ + "."
    for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix):
        print "Found submodule %s (is a package: %s)" % (modname, ispkg)
        module = __import__(modname, fromlist="dummy")
        print "Imported", module