To list all functions from a Python module, you can use several approaches depending on whether you want to use built-in functions or external libraries. Here’s a guide to help you retrieve and list functions from a module:
1. Using the dir()
Function
The built-in dir()
function returns a list of attributes and methods of an object, including functions within a module. Here’s how to use it:
import some_module
# List all attributes and methods in the module
all_attributes = dir(some_module)
# Filter to get only functions
functions = [attr for attr in all_attributes if callable(getattr(some_module, attr))]
print(functions)
2. Using the inspect
Module
The inspect module provides a more detailed way to retrieve functions from a module. You can use inspect.getmembers()
to get a list of all functions:
import inspect
import some_module
# Get all functions in the module
functions = [name for name, obj in inspect.getmembers(some_module) if inspect.isfunction(obj)]
print(functions)
3. Using globals()
for Current Module
If you want to list functions defined in the current module (not imported), you can use globals()
:
def func1():
pass
def func2():
pass
# List all functions in the current module
functions = [name for name, obj in globals().items() if callable(obj)]
print(functions)
4. Example: Listing Functions from the math
Module
import math
import inspect
# List all functions in the math module
functions = [name for name, obj in inspect.getmembers(math) if inspect.isfunction(obj)]
print(functions)
5. Summary
To list all functions from a Python module, you can use the dir()
function, the inspect module, or globals()
if dealing with the current module. Each approach provides a different level of detail and functionality based on your needs.