Skip to content

Instantly share code, notes, and snippets.

@tomschr
Last active May 20, 2017 20:36
Show Gist options
  • Save tomschr/22f56aa2028d9955fb9a4380f4cd386c to your computer and use it in GitHub Desktop.
Save tomschr/22f56aa2028d9955fb9a4380f4cd386c to your computer and use it in GitHub Desktop.
Lists all functions and classes from a loaded module
import pkgutil
import inspect
def members(module, predicate=None):
"""Yields all functions and classes of a module if predicate=None"""
def func_or_class(obj):
"""Inspects an object if it is a function or a class (=True),
otherwise False
"""
return inspect.isfunction(obj) or inspect.isclass(obj)
predicate = func_or_class if predicate is None else predicate
for _, func, in inspect.getmembers(module, predicate):
if func.__module__ == module.__name__:
yield func
def submodules(module, predicate=None):
"""Yields recursively sub module names from a given module
:param module: the given module; or, if you have only the name, use
sys.modules[NAME]
:type module: :class:`module`
"""
prefix = module.__name__ + "."
for importer, modname, ispkg in pkgutil.iter_modules(module.__path__, prefix):
module = importer.find_module(modname).load_module(modname)
yield from members(module, predicate)
if ispkg:
submodules(module, predicate)
del module
if __name__ == "__main__":
import ctypes
print(list(submodules(ctypes)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment