Skip to content

Instantly share code, notes, and snippets.

@twheys
Created June 7, 2017 11:57
Show Gist options
  • Save twheys/fc4d2e389a0a31eca53fc4846af5df2c to your computer and use it in GitHub Desktop.
Save twheys/fc4d2e389a0a31eca53fc4846af5df2c to your computer and use it in GitHub Desktop.
Small generator function that recursively scans a directory for all python modules.
def scan_for_modules(path):
"""
Generator function which scans a directory for all python modules and returns them successively.
"""
modules = []
for finder, pkgname, is_module in pkgutil.iter_modules([path]):
if pkgname in ['setup']:
continue
mod = importlib.import_module(pkgname)
if not hasattr(mod, '__path__'):
continue
yield mod
modules.append(mod)
while modules:
mod = modules.pop()
for finder, pkgname, is_module in pkgutil.iter_modules(mod.__path__):
child_mod = importlib.import_module('%s.%s' % (mod.__name__, pkgname))
yield child_mod
if is_module and 'test' != pkgname:
modules.append(child_mod)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment