🐍 Python Advanced

What are Python descriptors?

Why Interviewers Ask This

This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.

Answer

Descriptors are objects that define the behavior of attribute access through __get__, __set__, and __delete__ methods. Data descriptors define both __get__ and __set__ (and/or __delete__). Non-data descriptors define only __get__. Data descriptors have priority over instance __dict__. Example: class Validator: def __set_name__(self, owner, name): self.name = name; def __get__(self, obj, type=None): return obj.__dict__.get(self.name); def __set__(self, obj, value): if not isinstance(value, int): raise TypeError; obj.__dict__[self.name] = value. Python's built-in property, classmethod, staticmethod, and super() are all implemented as descriptors. Descriptors are the foundation of Python's attribute access system and enable reusable validation, computed attributes, and lazy loading.

Common Mistake

A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.