After you import a python module object by name in python source code dynamically ( How To Load / Import Python Package, Module Dynamically ), you must want to get all the module object attributes or functions. Then you can invoke the related module function or attributes in source code. This article will show you how to do it.
1. How To List All Functions Or Attributes Of Imported Python Module Steps.
- You can use python built-in dir(module_object) function to return all the module members include both function and attributes.
- You can also use python inspect module’s getmembers(module_object) function to get all module members, then use inspect module’s isfunction(object) function to check whether the module member is a function or not.
- Below is the example code, please see code comments for detail.
# Import getmembers, isfunction function from inspect module. from inspect import getmembers, isfunction # This function will list all the functions and attributes of the module. def list_module_attributes(mod_name): # First import the module object by module name. imported_module = __import__(mod_name, globals=None, locals=None, fromlist=True) # The dir() function will return all attributes and functions of the module object. mod_attrs_str = dir(imported_module) print(mod_attrs_str) ''' The inspect.getmembers() function will get all members of the module object. The inspect.isfunction() function will check whether the module member is a function or not. Below code will return module functions only. ''' functions_list = [o for o in getmembers(imported_module) if isfunction(o[1])] # Each element in the functions_list is a tuple object. for func in functions_list: # The first element of the tuple is the function name. print(func[0]) if __name__ == '__main__': list_module_attributes('lib.mod1')
Below is above example output.
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'method_1', 'method_2'] method_1 method_2