Sobes.tech
Junior — Middle

Can you explain what a descriptor is in Python and how it works?

sobes.tech AI

Answer from AI

In Python, a descriptor is an object that manages access to another object's attributes through the __get__, __set__, and __delete__ methods. Descriptors allow controlling the reading, writing, and deletion of attributes, implementing logic at the access level.

Here's 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__.get(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

    def __delete__(self, instance):
        raise AttributeError("Deletion is forbidden")

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

p = Person()
p.name = "Ivan"  # works
p.age = 30        # works
# p.age = 'thirty'  # will raise TypeError

Thus, descriptors are used to implement properties, validation, and other access control mechanisms for attributes.