How to list all functions in a Python module?

PythonServer Side ProgrammingProgramming

You can use the dir(module) to get all the attributes/methods of a module. For example,

>>> import math
>>> dir(math)
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

But here as you can see attributes of the module(__name__, __doc__, etc) are also listed. You can create a simple function that filters these out using the isfunction predicate and getmembers(module, predicate) to get the members of a module. For example,

>>> from inspect import getmembers, isfunction
>>> import helloworld
>>> print [o for o in getmembers(helloworld) if isfunction(o[1])]

Note that this doesn't work for built in modules as the type of functions for those modules is not function but built in function.

Published on 20-Dec-2017 07:30:32