10.1. Reflection About

  • Reflection is the ability of a program to examine and modify its own structure and behavior at runtime.

  • When accessing an attribute

  • setattr(obj, attrname, value) -> None

  • delattr(obj, attrname) -> None

  • getattr(obj, attrname, default) -> Any

  • hasattr(obj, attrname) -> bool

  • __setattr__(self, attrname, value) -> None

  • __delattr__(self, attrname) -> None

  • __getattribute__(self, attrname) -> Any

  • __getattr__(self, attrname) -> Any

Reflection is the ability of a program to examine and modify its own structure and behavior at runtime. In Python, reflection is supported through a number of built-in functions and modules.

The inspect module provides a set of functions for introspecting Python objects, such as classes, functions, and modules. These functions can be used to examine the attributes, methods, and source code of an object, as well as its inheritance hierarchy and type information.

10.1.1. What Happens When Accessing an Attribute

>>> class User:
...     pass
>>>
>>>
>>> x = User()

Setattr:

>>> x.name = 'Alice'

Hasattr:

>>> hasattr(x, 'name')
True

Getattr:

>>> x.name
'Alice'

Delattr:

>>> del x.name

10.1.2. Example 1

Here's an example of using the inspect module to examine the attributes and methods of a class:

>>> import inspect
>>> from pprint import pprint
>>>
>>>
>>> class MyClass:
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
...
...     def my_method(self, z):
...         return self.x + self.y + z
>>>
>>>
>>> result = inspect.getmembers(MyClass)
>>> pprint(result)
[('__class__', <class 'type'>),
 ('__delattr__', <slot wrapper '__delattr__'>),
 ('__dict__',
  mappingproxy({'__dict__': <attribute '__dict__'>,
                '__doc__': None,
                '__firstlineno__': 1,
                '__init__': <function MyClass.__init__ at 0x...>,
                '__module__': '__main__',
                '__static_attributes__': ('x', 'y'),
                '__weakref__': <attribute '__weakref__'>,
                'my_method': <function MyClass.my_method at 0x...>})),
 ('__dir__', <method '__dir__'>),
 ('__doc__', None),
 ('__eq__', <slot wrapper '__eq__'>),
 ('__firstlineno__', 1),
 ('__format__', <method '__format__'>),
 ('__ge__', <slot wrapper '__ge__'>),
 ('__getattribute__', <slot wrapper '__getattribute__'>),
 ('__getstate__', <method '__getstate__'>),
 ('__gt__', <slot wrapper '__gt__'>),
 ('__hash__', <slot wrapper '__hash__'>),
 ('__init__', <function MyClass.__init__ at 0x...>),
 ('__init_subclass__',
  <built-in method __init_subclass__ of type object at 0x...0>),
 ('__le__', <slot wrapper '__le__'>),
 ('__lt__', <slot wrapper '__lt__'>),
 ('__module__', '__main__'),
 ('__ne__', <slot wrapper '__ne__'>),
 ('__new__', <built-in method __new__ of type object at 0x...>),
 ('__reduce__', <method '__reduce__'>),
 ('__reduce_ex__', <method '__reduce_ex__'>),
 ('__repr__', <slot wrapper '__repr__'>),
 ('__setattr__', <slot wrapper '__setattr__'>),
 ('__sizeof__', <method '__sizeof__'>),
 ('__static_attributes__', ('x', 'y')),
 ('__str__', <slot wrapper '__str__'>),
 ('__subclasshook__',
  <built-in method __subclasshook__ of type object at 0x...0>),
 ('__weakref__', <attribute '__weakref__'>),
 ('my_method', <function MyClass.my_method at 0x...>)]

In this example, the getmembers() function from the inspect module is used to examine the attributes and methods of the MyClass class. The output shows a list of tuples, where each tuple contains the name and value of an attribute or method of the class.

10.1.3. Example 2

Another way to use reflection in Python is through the getattr() and setattr() built-in functions. These functions allow you to get and set attributes of an object dynamically at runtime, based on their name.

Here's an example of using getattr() and setattr() to get and set attributes of an object:

>>> class MyClass:
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
>>>
>>> # Create an instance of MyClass
>>> obj = MyClass(1, 2)
>>>
>>> # Use getattr to get the value of an attribute dynamically
>>> x_value = getattr(obj, 'x')
>>> print(x_value)
1
>>>
>>> # Use setattr to set the value of an attribute dynamically
>>> setattr(obj, 'y', 3)
>>> print(obj.y)
3

In this example, getattr() is used to get the value of the x attribute of the obj instance of MyClass, and setattr() is used to set the value of the y attribute of obj to 3.

10.1.4. Protocol

>>> from typing import Protocol
>>>
>>> class MyClass(Protocol):
...     def __setattr__(self, attrname, value): ...
...     def __delattr__(self, attrname): ...
...     def __getattribute__(self, attrname): ...
...     def __getattr__(self, attrname): ...

10.1.5. Problem

>>> class Point:
...     x = property()
...     y = property()
...     z = property()
...
...     @x.setter
...     def x(self, value):
...         if value < 0:
...             raise ValueError('Coordinate cannot be negative')
...         self._x = value
...
...     @x.getter
...     def x(self):
...         return self._x
...
...     @y.setter
...     def y(self, value):
...         if value < 0:
...             raise ValueError('Coordinate cannot be negative')
...         self._y = value
...
...     @y.getter
...     def y(self):
...         return self._y
...
...     @z.setter
...     def z(self, value):
...         if value < 0:
...             raise ValueError('Coordinate cannot be negative')
...         self._z = value
...
...     @z.getter
...     def z(self):
...         return self._z
>>>
>>>
>>> pt = Point()
>>> pt.x = 1
>>> pt.y = 2
>>> pt.z = 3
>>>
>>> pt.x = -1
Traceback (most recent call last):
ValueError: Coordinate cannot be negative
>>>
>>> pt.y = -2
Traceback (most recent call last):
ValueError: Coordinate cannot be negative
>>>
>>> pt.z = -3
Traceback (most recent call last):
ValueError: Coordinate cannot be negative