Python Inspect ModuleIn this tutorial, we will learn about the Python's inspect module and its functions. It module is used to examine the objects within our code. As we know, Python operates as an object-oriented language and our code revolves around these objects, the inspect module becomes valuable for identifying particular modules or objects. It proves particularly useful for examining specific function calls or tracebacks, which in turn facilitates smoother debugging processes. The inspect module offers a range of methods that can be divided into two main categories: methods for confirming the type of token, and methods for fetching the source of the token. Methods to verify the type of TokenBelow are the methods to verify the type of the token -
Let's understand the following example - Example - Output: Is MyClass a class - True Is my_function a class - False In this example, the isclass() method is used to check whether the MyClass and my_function objects are classes. The results will be True for MyClass (since it's a class) and False for my_function (since it's not a class).
Example - Output: Is math a module - True Is 'hello' a module - False
Example - Output: Is my_function a function - True Is print a function - True
Example - Output: Is my_method a method - True Is my_function a method - False Method to Retrieves the Source of Tokengetclasstree(): The getclasstree()` function is useful for obtaining and examining the hierarchy of classes. It provides a tuple that includes the class itself and its parent classes. When paired with the getmro() function, which returns the parent classes, it aids in comprehending the class hierarchy. Example - Output: [(<class '__main__.D'>, (<class '__main__.C'>,)), (<class '__main__.B'>, (<class '__main__.A'>,))] Explanation - In the above code -
Example: Output: Members of my_function: [('__annotations__', {}), ('__call__', <method-wrapper '__call__' of function object at 0x7f3d91d76ca0>), ('__class__', <class 'function'>), ... ] Members of MyClass: [('__class__', <class 'type'>), ('__delattr__', <slot wrapper '__delattr__' of 'object' objects>), ('__dict__', <attribute '__dict__' of 'MyClass' objects>), ... ] In this code, the `getmembers()` function is used to retrieve the members of both the `my_function` function and the `MyClass` class. The output displays the list of members for each of these entities. We can also get the members of a module. Example - 2: Output: [('CLOCK_BOOTTIME', 7), ('CLOCK_MONOTONIC', 1), ('CLOCK_MONOTONIC_RAW', 4), ('CLOCK_PROCESS_CPUTIME_ID', 2), ('CLOCK_REALTIME', 0), ('CLOCK_TAI', 11), ('CLOCK_THREAD_CPUTIME_ID', 3), ('_STRUCT_TM_ITEMS', 11), ('__doc__', 'This module provides various functions to manipulate time values.\n\nThere are two standard representations of time. One is the number\nof seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\nor a floating point number (to represent fractions of seconds).\nThe Epoch is system-defined; on Unix, it is generally January 1st, 1970.\nThe actual value can be retrieved by calling gmtime(0).\n\nThe other representation is a tuple of 9 integers giving local time.\nThe tuple items are:\n year (including century, e.g. 1998)\n month (1-12)\n day (1-31)\n hours (0-23)\n minutes (0-59)\n seconds (0-59)\n weekday (0-6, Monday is 0)\n Julian day (day in the year, 1-366)\n DST (Daylight Savings Time) flag (-1, 0 or 1)\nIf the DST flag is 0, the time is given in the regular time zone;\nif it is 1, the time is given in the DST time zone;\nif it is -1, mktime() should guess based on the date and time.\n'), ('__loader__', <class '_frozen_importlib.BuiltinImporter'>), ('__name__', 'time'), ('__package__', ''), ('__spec__', ModuleSpec(name='time', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in')), ('altzone', 0), ('asctime', <built-in function asctime>), ('clock_getres', <built-in function clock_getres>), ('clock_gettime', <built-in function clock_gettime>), ('clock_gettime_ns', <built-in function clock_gettime_ns>), ('clock_settime', <built-in function clock_settime>), ('clock_settime_ns', <built-in function clock_settime_ns>), ('ctime', <built-in function ctime>), ('daylight', 0), ('get_clock_info', <built-in function get_clock_info>), ('gmtime', <built-in function gmtime>), ('localtime', <built-in function localtime>), ('mktime', <built-in function mktime>), ('monotonic', <built-in function monotonic>), ('monotonic_ns', <built-in function monotonic_ns>), ('perf_counter', <built-in function perf_counter>), ('perf_counter_ns', <built-in function perf_counter_ns>), ('process_time', <built-in function process_time>), ('process_time_ns', <built-in function process_time_ns>), ('pthread_getcpuclockid', <built-in function pthread_getcpuclockid>), ('sleep', <built-in function sleep>), ('strftime', <built-in function strftime>), ('strptime', <built-in function strptime>), ('struct_time', <class 'time.struct_time'>), ('thread_time', <built-in function thread_time>), ('thread_time_ns', <built-in function thread_time_ns>), ('time', <built-in function time>), ('time_ns', <built-in function time_ns>), ('timezone', 0), ('tzname', ('UTC', 'UTC')), ('tzset', <built-in function tzset>)]
Example: Output: Function signature: (x, y=0, *args, **kwargs) In this example, the `signature()` function is utilized to determine the signature of the my_function() function. The output displays the signature of the function, including its parameters and special argument types. stack(): The `stack()` function assists in inspecting the interpreter stack, revealing the sequence in which functions were invoked. Example - Output: Function call stack: [FrameInfo(frame=<frame at 0x7f785c0ad8e0, file 'example.py', line 6, code function function_two>, filename='example.py', lineno=6, function='function_two', code_context=[' function_two()\n'], index=0), ...] In this example, the `stack()` function is used to retrieve and display information about the call stack. The output provides details about the frames in the stack, including file locations, line numbers, and function names. Example - 2: Output: Function call stack: [FrameInfo(frame=<frame at 0x7f6d59cc0b80, file '<string>', line 13, code main>, filename='<string>', lineno=12, function='main', code_context=None, index=None, positions=Positions(lineno=12, end_lineno=12, col_offset=19, end_col_offset=34)), FrameInfo(frame=<frame at 0x7f6d59a22ca0, file '<string>', line 18, code <module>>, filename='<string>', lineno=18, function='<module>', code_context=None, index=None, positions=Positions(lineno=18, end_lineno=18, col_offset=0, end_col_offset=6))] Fibonacci result: 5
Example - Output: Source code of MyClass: class MyClass: def __init__(self, value): self.value = value def get_value(self): return self.value In this example, the `getsource()` function is utilized to retrieve and display the source code of the `MyClass` class. The output presents the source code of the class, including its methods and attributes.
Example - Output: Module name of my_function: __main__ In this example, the `getmodule()` function is used to retrieve the module name of the `my_function` function. The output displays the name of the module in which the function is defined.
Example: Output: Documentation of my_function: This is a sample function. ConclusionIn conclusion, the `inspect` module is a very useful library for Python programmers. It helps them look closely at different parts of their code, like classes, functions, and more. This allows the developer to understand what's happening inside and fix any problems. Whether they want to check out how things are connected, see the actual code, or understand how functions work, the `inspect` module has got them covered. Next TopicStruct Module in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India