How To Get All The Function Name In Python

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:

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:

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:

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:

Method 2 – Using the dir() function:

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.