Sobes.tech
Junior — Middle

Can you explain what the term 'descriptor' means in the context of Python and how it works?

sobes.tech AI

Answer from AI

In Python, a descriptor is an object that manages access to attributes of another object. It implements one or more special methods: __get__, __set__, and __delete__. When an attribute with a descriptor is accessed, set, or deleted, the corresponding descriptor methods are called.

This allows controlling the behavior of attributes, for example, implementing computed properties, value validation, or lazy initialization.

An example of a simple descriptor for type checking:

class Typed:
    def __init__(self, name, expected_type):
        self.name = name
        self.expected_type = expected_type

    def __get__(self, instance, owner):
        return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if not isinstance(value, self.expected_type):
            raise TypeError(f"Expected type {self.expected_type.__name__}")
        instance.__dict__[self.name] = value

class Person:
    age = Typed('age', int)

p = Person()
p.age = 30  # works
# p.age = 'thirty'  # raises TypeError

Thus, descriptors are a powerful tool for managing access to attributes in Python.