Introspection in Python29 Aug 2024 | 5 min read In this tutorial, we will learn about introspection which is a greatest strength of the Python programming language. Let's have a brief introduction to the introspection. What is Introspection?Introspection is a technique to determine the type of an object at runtime. As we know, everything in Python is an object and has wide support for various introspection methods. It is a code that inspects other modules and functions in memory as objects, getting information about them and manipulating them. It provides the facility to get familiar with an object's properties and attributes. By using introspection, we can dynamically inspect Python objects. Python is a dynamic, object-oriented, introspection support language that runs deep and wide throughout. The introspection feature makes it a more powerful language than others. Python provides several functions and utilities for code introspection. We can also define call functions and reference functions with the no-name. The dir() FunctionThe dir() function returns a sorted list of the attributes and methods belonging to an object. Let's understand the following example, which uses the dir() function to return the names of all methods that can be used in a given program. Example - Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] The dir() function returns all the methods and attributes used by the list object. Example - 2: Output: The methods and attributes are used with integer: ['__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'] The methods and attributes are used with string: ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] Python type() functionThe type() function returns the type of the object. Let's understand the following example. Example - Output: <class 'int'> <class 'str'> Example - 2: Output: <class 'int'> <class 'str'> <class 'list'> <class 'dict'> <class 'tuple'> <class 'type'> <class 'function'> <class 'type'> <class '__main__.MyClass'> <class 'module'> Python hasattr() FunctionThe hasattr() function checks if the object has an attribute. Depending upon the result, it returns either true or false if the object has a given attribute. Let's understand the following example. Example - Output: True False Python id() FunctionThe id() function returns the special id of an object. Let's understand the following example. Example - Output: The integer id is: 140736928548512 The string id is: 2423227163376 The list id is: 2423232862400 The set id is: 2423232820480 The list id is: 2423226957888 The object id is: 140736928328528 The functio id is: 2423231111520 The MyClass id is: 2423225796064 The obj id is: 2423232892640 The sys module id is: 2423227235840 Python sys ModuleThe sys module allows us to interaction with the system specific variables and function used or maintained by the interpreter and to function that interact strongly with the interpreter. Let's understand the following example. Example - Output: 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)] win32 ['d:\\Python Project', 'D:\\python_project\\Myfirstdjangoproject\\Hello', 'c:\\users\\User\\appdata\\local\\programs\\python\\python38\\python38.zip', 'c:\\users\\User\\appdata\\local\\programs\\python\\python38\\DLLs', 'c:\\users\\User\\appdata\\local\\programs\\python\\python38\\lib', 'c:\\users\\User\\appdata\\local\\programs\\python\\python38', 'C:\\Users\\User\\.virtualenvs\\Django-ExvyqL3O', 'C:\\Users\\User\\.virtualenvs\\Django-ExvyqL3O\\lib\\site-packages'] We inspect the Python version, platform, and search path locations in the above code. Some Other Introspection MethodsThere are some other important introspection methods which are given below.
Introspection Attributes in PythonWe are going to discuss some attributes that give useful information about objects. Let's see some important introspection attribute.
ConclusionWe have discussed what introspection is and how it is important. We have seen some important methods and examples. To learn more about introspection, you can check the Python inspect module. Next TopicClass Decorator in Python |
A binary search tree is a descendent of a more general binary tree with some constraints. In a binary search tree, the arrangement of nodes should follow certain properties. These properties are: All the parent nodes of the tree should have greater value than the child node...
13 min read
In the following tutorial, we will discuss the rarfile module of the Python programming language. We will understand the different classes of the rarfile module along with some examples. So, let's get started. Understanding the Python rarfile module The is used to read the RAR archive. The interface...
10 min read
These days, a great many people who need to become Python developers know the linguistic structure of Python. Because of the plenty of instructional exercises accessible on the web. Some people have zero ideas about making projects. In any chance that you're also one of them,...
10 min read
Introduction: In this article, we are discussing parsing data in python. All programming languages parse tokens into a significant lexical shape so that a compiler or interpreter can transform the tokens into meaningful output. This article examines parsing in Python and the modules that assist with parsing...
3 min read
In this tutorial, we will discuss how to write a Python program to find the number of days between two given numbers. Suppose we have given two dates our expected output would be: Example: Input: Date_1 = 12/10/2021, Date_2 = 31/08/2022 Output: Number of Days between the given Dates are:...
4 min read
In this tutorial, we will learn how to improve the object-oriented design in Python. When we write classes and design the interaction in Python, we follow a set of instructions that helps to build better object-oriented code. Object-oriented design is one of the popular and widely...
13 min read
Of the seven types of AI that illustrate the different ways that AI is implemented, one of the most popular is the recognition pattern. The principle behind recognition patterns recognized the pattern in AI involves using machine-learning as well as cognitive technologies to categorize and...
7 min read
Machine learning is a science of programming the computer by which they can learn from different types of data. According to machine learning's definition of Arthur Samuel - "Field of study that gives computers the ability to learn without being explicitly programmed". The concept of machine...
12 min read
We have used different numeric data types in Python, in this tutorial we will learn how we can convert a float value to an integer value. Let's have a look at the approaches to implement the same- Using trunc() Using floor() Using ceil() Using int() So, let's get started with the first...
4 min read
os.getenv() is a Python function that is used to retrieve the value of an environment variable. An environment variable is a key-value pair that is stored in the operating system's environment, which is a collection of variables that affect the behavior of processes running on the...
3 min read
We request you to subscribe our newsletter for upcoming updates.
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