List classes, methods and functions in a module (Python recipe) by Anand
The recipe provides a method «describe» which takes a module as argument and describes classes, methods and functions in the module. The method/function description provides information on the function/method arguments using the inspect module.
Copy to clipboard
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
#!/usr/bin/env python # Describe classes, methods and functions in a module. # Works with user-defined modules, all Python library # modules, including built-in modules. import inspect import os, sys INDENT=0 def wi(*args): """ Function to print lines indented according to level """ if INDENT: print ' '*INDENT, for arg in args: print arg, print def indent(): """ Increase indentation """ global INDENT INDENT += 4 def dedent(): """ Decrease indentation """ global INDENT INDENT -= 4 def describe_builtin(obj): """ Describe a builtin function """ wi('+Built-in Function: %s' % obj.__name__) # Built-in functions cannot be inspected by # inspect.getargspec. We have to try and parse # the __doc__ attribute of the function. docstr = obj.__doc__ args = '' if docstr: items = docstr.split('\n') if items: func_descr = items[0] s = func_descr.replace(obj.__name__,'') idx1 = s.find('(') idx2 = s.find(')',idx1) if idx1 != -1 and idx2 != -1 and (idx2>idx1+1): args = s[idx1+1:idx2] wi('\t-Method Arguments:', args) if args=='': wi('\t-Method Arguments: None') print def describe_func(obj, method=False): """ Describe the function object passed as argument. If this is a method object, the second argument will be passed as True """ if method: wi('+Method: %s' % obj.__name__) else: wi('+Function: %s' % obj.__name__) try: arginfo = inspect.getargspec(obj) except TypeError: print return args = arginfo[0] argsvar = arginfo[1] if args: if args[0] == 'self': wi('\t%s is an instance method' % obj.__name__) args.pop(0) wi('\t-Method Arguments:', args) if arginfo[3]: dl = len(arginfo[3]) al = len(args) defargs = args[al-dl:al] wi('\t--Default arguments:',zip(defargs, arginfo[3])) if arginfo[1]: wi('\t-Positional Args Param: %s' % arginfo[1]) if arginfo[2]: wi('\t-Keyword Args Param: %s' % arginfo[2]) print def describe_klass(obj): """ Describe the class object passed as argument, including its methods """ wi('+Class: %s' % obj.__name__) indent() count = 0 for name in obj.__dict__: item = getattr(obj, name) if inspect.ismethod(item): count += 1;describe_func(item, True) if count==0: wi('(No members)') dedent() print def describe(module): """ Describe the module object passed as argument including its classes and functions """ wi('[Module: %s]\n' % module.__name__) indent() count = 0 for name in dir(module): obj = getattr(module, name) if inspect.isclass(obj): count += 1; describe_klass(obj) elif (inspect.ismethod(obj) or inspect.isfunction(obj)): count +=1 ; describe_func(obj) elif inspect.isbuiltin(obj): count += 1; describe_builtin(obj) if count==0: wi('(No members)') dedent() if __name__ == "__main__": import sys if len(sys.argv)2: sys.exit('Usage: %s ' % sys.argv[0]) module = sys.argv[1].replace('.py','') mod = __import__(module) describe(mod)
This came as a question in our local Python mailing list (BangPypers). I wrote up the above solution to provide a quick summary of a module in terms of classes, and simple method descriptions. The ‘inspect’ module makes this task relatively easy.
[Edit] — Added support for built-in functions/methods. [Edit 22/10/08] — Changes in printing style.List All the Methods of a Python Module
- List All the Methods of a Python Module Using the dir() Method
- List All the Methods of a Python Module Using the inspect() Module
A Python module, package, or library is a file or group of files containing definitions of Python functions, Python classes, and Python variables. In Python, we can import a module and use its implementations to stick with two important concepts of the world of computer science; Don’t reinvent the wheel and Don’t repeat yourself .
These packages or modules can be as small as a few lines and as big as millions of lines. As the size grows, it becomes difficult to analyze modules or see a clear outline of the content of the package. But Python developers have solved that problem for us as well.
In Python, there are many ways in which we can list down methods and classes of a Python module. In this article, we will talk about two such practices with the help of relevant examples. Note that, for instance, we will consider the NumPy Python module. If you don’t have the NumPy package on your system or virtual environment, you can download it using either the pip install numpy or the pip3 install numpy command.
List All the Methods of a Python Module Using the dir() Method
The dir() method is an in-built method in Python. It prints all the attributes and methods of an object or a Python package. Check the following code to understand it.
class A: a = 10 b = 20 c = 200 def __init__(self, x): self.x = x def get_current_x(self): return self.x def set_x(self, x): self.x = x def __repr__(self): return f"X: x>" print(dir(int)) print(dir(float)) print(dir(A))
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] ['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real'] ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'c', 'get_current_x', 'set_x']
We can use the dir() method to list down all the module methods. Refer to the following code to see how.
import numpy print("NumPy Module") print(dir(numpy))
As we can see, the dir() method has listed all the NumPy methods.
List All the Methods of a Python Module Using the inspect() Module
The inspect module is a Python module that has several helpful functions to get useful information about modules, classes, class objects, functions, tracebacks, and objects. We can use this module for our simple purpose. Refer to the following code to learn about its usage.
import numpy from inspect import getmembers, isfunction print("NumPy Module") print(getmembers(numpy, isfunction))
- ismodule() : Return True if the object is a module.
- isclass() : Return True if the object is a class.
- istraceback() : Return True if the object is a traceback.
- isgenerator() : Return True if the object is a generator.
- iscode() : Return True if the object is a code.
- isframe() : Return True if the object is a frame.
- isabstract() : Return True if the object is an abstract base class.
- iscoroutine() : Return True if the object is a coroutine.
To learn more about this module, refer to the official documentation.
Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.