To print all functions of a specific module in Python, you can either use the inspect module or the dir() built-in method.
There are use cases in which you must understand where you should use the inspect module and where you should use the dir() method.
If you are working with a custom module and need to list all the functions it contains, always use the inspect module.
If you want to list all attributes (functions, constants, etc.) in the built-in modules, you can opt for the dir() method.
Method 1: Using inspect
The inspect module provides inspect.isfunction() method that you can use to identify the callable objects, such as functions.
Approach
- Import the built-in inspect module.
- Import your other module, which you want to inspect—meaning, whose functions you want to list.
- Use inspect.getmembers() to get all members of the module.
- Finally, filter the members using the inspect.isfunction() to list only methods.
Here is our custom module “my_module.py” that contains all the functions:
# my_module.py def add(x, y): return x + y def greet(name): return f"Hola, {name}!" def multiply(a, b): return a * b class MyClass: def method(self): pass
You can see that the above file contains three functions and one class method. We want to list all three functions in another file.
Create another file called “inspect.py” in the same directory as “my_module.py” and add the code below:
import inspect import my_module # Get all members of the module and filter for functions functions = [name for name, obj in inspect.getmembers(my_module, inspect.isfunction)] # Print the list of function names print("Functions in my_module:") for func in functions: print(func) # Output: # Functions in my_module: # add # greet # multiply
In the above code, we create a new list using list comprehension and use the .getmembers() function to retrieve all methods and attributes.
We then apply the .isfunction() method to filter out only functions (not class methods, attributes, or other callable objects) and return the resulting list.
The resulting list contains only functions of that module, and as you can see from the output, “add”, “greet”, and “multiply” are those functions.
Method 2: Using dir()
The dir() function gives all names in the module (functions, variables, classes, etc.). With the help of getattr() callable(), isinstance(), and types.FunctionType() function, we can only print the list of function names.
import my_module import types all_names = dir(my_module) # Filter only regular functions, exclude classes and others functions = [ name for name in all_names if isinstance(getattr(my_module, name), types.FunctionType) ] # Print the list of function names print("Functions in my_module:") for func in functions: print(func) # Output: # Functions in my_module: # add # greet # multiply
That’s all!