Is there a straightforward way to list the names of all modules in a package, without using
__all__
/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py
>>> package_contents("testpkg")
['modulea', 'moduleb']
Maybe this will do what you're looking for?
import imp
import os
MODULE_EXTENSIONS = ('.py', '.pyc', '.pyo')
def package_contents(package_name):
file, pathname, description = imp.find_module(package_name)
if file:
raise ImportError('Not a package: %r', package_name)
# Use a set because some may be both source and compiled.
return set([os.path.splitext(module)[0]
for module in os.listdir(pathname)
if module.endswith(MODULE_EXTENSIONS)])