In Python, it is sometimes useful to get the names of all functions within a module or a script, especially when working with large codebases. This tutorial will guide you through the process of obtaining the names of all functions in Python using two different approaches: Using the inspect
module and Using the dir()
function.
Step 1: Using the inspect
module
The inspect
module provides several functions that help in getting live information about live objects such as modules, classes, and functions. In this example, we will use the inspect
module to get the names of all functions in a module.
First, you need to import the inspect
module:
1 |
import inspect |
Next, to get the functions in the current module, you can use the inspect.getmembers()
function, which returns a list of tuples, with the first element being the name of the function and the second element containing the actual function object. You can filter the required functions using the inspect.isfunction()
function. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 |
import inspect def test_function1(): pass def test_function2(): pass functions_list = inspect.getmembers(sys.modules[__name__], inspect.isfunction) print(functions_list) |
The output will display a list of functions:
[('test_function1', ), ('test_function2', )]
Step 2: Using the dir()
function
The dir()
function returns the list of names in the current local scope, which includes variables, functions, and classes. You can use this function to gather the names of functions within a given scope. To filter out the functions, we will use the callable()
function, which checks if the object appears to be callable (i.e., can be called as a function or method).
Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 |
import sys def test_function1(): pass def test_function2(): pass functions_list = [func_name for func_name in dir(sys.modules[__name__]) if callable(getattr(sys.modules[__name__], func_name))] print(functions_list) |
This method will return a list of function names:
['test_function1', 'test_function2']
Full Code:
Here is the complete code for both methods:
Method 1 – Using the inspect
module:
1 2 3 4 5 6 7 8 9 10 11 12 |
import inspect import sys def test_function1(): pass def test_function2(): pass functions_list = inspect.getmembers(sys.modules[__name__], inspect.isfunction) print(functions_list) |
Method 2 – Using the dir()
function:
1 2 3 4 5 6 7 8 9 10 11 |
import sys def test_function1(): pass def test_function2(): pass functions_list = [func_name for func_name in dir(sys.modules[__name__]) if callable(getattr(sys.modules[__name__], func_name))] print(functions_list) |
Conclusion
In this tutorial, we have demonstrated two different methods to get the names of all functions in a Python module: using the inspect
module and the dir()
function. Both methods are useful depending on your needs and can help in managing and navigating large codebases effectively.