Home » Posts tagged 'Python class introspection'

Tag Archives: Python class introspection

Newly Updated Posts

Python Reflection

In Python, you can perform reflection, which is the ability to examine and modify the structure and behavior of an object at runtime. Python provides several built-in functions and modules that allow you to perform reflection operations. Here are some common reflection techniques in Python:

1.Getting the type of an object:

You can use the built-in type() function to determine the type of an object. For example:

x = 42
print(type(x))  # <class 'int'>
2. Getting the list of attributes and methods:
The built-in dir() function returns a list of attributes and methods of an object. You can use it to explore the available members of an object. For example:
x = [1, 2, 3]
print(dir(x))  # ['__add__', '__class__', '__contains__', ...]

3. Checking if an attribute or method exists:

The hasattr() function allows you to check if an object has a specific attribute or method. It takes the object and the attribute name as arguments and returns a boolean value. For example:

x = [1, 2, 3]
print(hasattr(x, 'append'))  # True
print(hasattr(x, 'sort'))  # True
print(hasattr(x, 'foobar'))  # False

4. Getting and setting attribute values dynamically:

You can use the built-in getattr() and setattr() functions to get and set attribute values dynamically. getattr() takes the object and the attribute name as arguments and returns the value of the attribute. setattr() takes the object, the attribute name, and the new value as arguments and sets the attribute to the new value. For example:

class MyClass:
    x = 42

obj = MyClass()
print(getattr(obj, 'x'))  # 42
setattr(obj, 'x', 24)
print(obj.x)  # 24

5. Inspecting function arguments and parameters:

The inspect module provides functions for inspecting live objects, including functions and classes. You can use it to access information about the arguments and parameters of functions. For example:

import inspect

def my_function(a, b, c=0):
    pass

signature = inspect.signature(my_function)
print(signature.parameters)  # OrderedDict([('a', <Parameter "a">), ('b', <Parameter "b">), ('c', <Parameter "c=0">)])

These are just a few examples of reflection capabilities in Python. Python’s dynamic nature and rich standard library provide many more options for performing reflection operations based on your specific requirements.