From protocol knowledge to production patterns
The descriptor protocol is abstract until you build something with it. Once you can write a field that validates on assignment, a property that computes once and caches, a model column that knows its database type, and a configuration field that falls back to an environment variable, the interview stops being trivia and becomes a design conversation. Interviewers who open with descriptors usually plan to extend your implementation live โ "now make it support defaults," "now invalidate the cache when width changes" โ so the goal is a clean skeleton that bends gracefully. This lesson focuses on the four patterns that appear most often and on the extension points they should expose.
Prerequisites
- !The descriptor lookup chain and data versus non-data descriptors
- !properties and __set_name__
What You'll Learn
- 1Implement a reusable validated-field descriptor hierarchy
- 2Write cached-property and time-to-live descriptors that store state on instances
- 3Sketch an ORM-style model where columns are descriptors collected at class creation
- 4Design configuration fields that read environment variables with type coercion
Pattern one: validated fields
Validation logic duplicated across __init__, setters, and API layers is the problem descriptors solve. The design is a small abstract base implementing __set_name__, __get__, and __set__, delegating the actual check to a validate method that subclasses override. The base owns storage: assignment writes to _{name} on the instance after validation passes. Subclasses like NonEmptyString, PositiveNumber, and Email become one-liners, and a model class composes them as class attributes. Composition beats clever inheritance here: keep the base dumb and push every policy decision into the subclasses so adding a new field type never touches the machinery.
Two design decisions matter in the interview. First, where does normalization live? Trimming whitespace, lower-casing emails, and coercing numeric strings all belong inside validate โ return the cleaned value, not the raw input. Second, how do errors identify the offending field? The descriptor knows its public name via __set_name__, so raising ValueError(f"{self.name} must be positive") gives callers actionable messages without any wrapper code. A strong follow-up answer is that modern codebases might use pydantic or attrs for this exact job, and that understanding descriptors explains why those libraries work.
class Validated:
"""Base descriptor: validate on set, store on the instance."""
def __set_name__(self, owner, name):
self.name = name
self.private = f"_{name}"
def __get__(self, obj, objtype=None):
if obj is None:
return self
return getattr(obj, self.private, None)
def __set__(self, obj, value):
setattr(obj, self.private, self.validate(value))
def validate(self, value):
raise NotImplementedError
class PositiveNumber(Validated):
def validate(self, value):
if not isinstance(value, (int, float)):
raise TypeError(f"{self.name} must be a number")
if value <= 0:
raise ValueError(f"{self.name} must be positive")
return value
class NormalizedEmail(Validated):
def validate(self, value):
if not isinstance(value, str) or "@" not in value:
raise ValueError(f"{self.name} must be a valid email")
return value.strip().lower()
class Account:
email = NormalizedEmail()
balance = PositiveNumber()
def __init__(self, email, balance):
self.email = email
self.balance = balance
acct = Account(" [email protected] ", 100)
print(acct.email) # [email protected]
Pattern two: caching computed attributes
Expensive derived attributes โ a parsed document tree, an aggregated report, a cryptographic fingerprint โ should compute once per object. A cached-property descriptor stores the result in obj.__dict__[name] on first access and returns the stored value thereafter. Because the instance dictionary now holds the name, some implementations return a non-data descriptor and let the dictionary short-circuit lookups entirely; others check the dictionary inside __get__ for clarity. Either way, the critical rule is that cache state lives on the instance, never on the shared descriptor.
Time-to-live caching adds a timestamp beside the value and recomputes when the entry goes stale, a pattern straight out of configuration clients and rate-limited API wrappers. A more sophisticated variant tracks dependencies: the descriptor records the values of named attributes at computation time and recomputes when any of them changes. In an interview, dependency-tracked caching is a great place to show you can extend a simple design โ point out that the alternative is invalidation hooks on every mutator, which does not scale.
import time
class cached_property:
"""Compute once per instance; cache in the instance dict."""
def __init__(self, func):
self.func = func
self.attrname = None
def __set_name__(self, owner, name):
self.attrname = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.attrname not in obj.__dict__:
obj.__dict__[self.attrname] = self.func(obj)
return obj.__dict__[self.attrname]
class Report:
def __init__(self, rows):
self.rows = rows
@cached_property
def total(self):
print("computing total...")
return sum(row["amount"] for row in self.rows)
report = Report([{"amount": 10}, {"amount": 32}])
print(report.total) # computes
print(report.total) # cached
Pattern three: ORM-style model columns
Every major Python ORM expresses columns as descriptors: a StringField(max_length=100) class attribute that validates types, enforces nullability, and remembers the SQL column type so a metaclass can collect field definitions and generate CREATE TABLE statements. Rebuilding a toy version in an interview is highly effective. The metaclass (or __init_subclass__) scans the class namespace for Field instances, stores them in a _fields dict, and the base model's __init__ and save methods iterate that dict instead of hard-coding column names.
The design point to articulate: descriptors are the bridge between declarative class-level configuration and per-instance data. The field object is shared โ it carries metadata โ while values live on each instance under names the field itself manages. Once the audience sees that split, extending the toy ORM with defaults, primary keys, or lazy loading feels like filling in blanks rather than inventing architecture.
Pattern four: environment-backed configuration
Application configuration that reads os.environ with type coercion is another descriptor showcase. A ConfigField(default=8000, env_var="APP_PORT") attribute checks the environment on first access, converts "true"/"42" to real types, caches the result on the instance, and validates explicit assignments. Precedence โ environment beats default, explicit assignment beats both โ is exactly the sort of requirement interviewers throw at you mid-question, and a descriptor handles it in one clean __get__.
This is the pattern behind Django settings objects and many twelve-factor app configs. When you present it, mention the testability benefit: tests can monkeypatch os.environ and instantiate a fresh config object rather than mutating global module state. That comment often steers the conversation toward testing practice, which is rarely a downside.
Extending your descriptors under pressure
Expect follow-ups that mutate your design. "Add a default value" means getattr(obj, self.private, self.default) in __get__. "Make it thread-safe" means a per-instance lock stored beside the value. "Support inheritance" means subclasses inherit the class attribute naturally โ descriptors already participate in the MRO โ but cached values in __dict__ remain per-subclass-instance, which usually just works. "Work with __slots__" is the trap: slotted classes have no __dict__, so your descriptor must either require a designated slot for storage or use a WeakKeyDictionary keyed by instance. Naming that constraint before the interviewer does is a senior-level move.
Another common extension is serialization: a descriptor that exposes a to_dict hook lets a model dump only public validated fields, skipping private storage names automatically. And when the interviewer asks about equality or hashing, point out that descriptors change attribute access, not object identity โ __eq__ and __hash__ remain yours to define on the model class, and caching a derived attribute must never feed into hash computation or the object's hash can drift after first access.
| Pattern | Descriptor role | State lives | Common extension |
|---|---|---|---|
| Validated field | Intercepts set | Instance private attribute | Normalization, coercion |
| Cached property | Intercepts get | Instance dict | TTL, dependency invalidation |
| ORM column | Metadata + storage | Instance private attribute | Defaults, SQL type mapping |
| Config field | Fallback chain in get | Instance cache | Type coercion, secrets lookup |
Common Mistakes
Caching values on the descriptor object itself
Fix: Store on the instance; descriptors are shared by every instance of the class
Ignoring __slots__ classes that have no __dict__
Fix: Use a designated slot or WeakKeyDictionary storage, and document the requirement
Validation that raises before normalizing
Fix: Normalize and validate in one validate method that returns the cleaned value
Forgetting that inheritance shares the descriptor but not the instance state
Fix: Rely on instance dictionaries for per-object data; test with subclass instances early
Best Practices
- Start every descriptor with __set_name__ โ it removes an entire category of naming bugs
- Keep descriptors small; put policy (what is valid, how long a TTL lasts) in arguments or subclasses
- Test class-level access (Class.attr) as well as instance access
- Mention pydantic or attrs when asked about validation so the interviewer knows you know the ecosystem
Interview Questions
Q1: Implement a cached property in ten lines.
A non-data descriptor with __set_name__ recording the attribute name and __get__ that computes via the wrapped function and stores the result in obj.__dict__[name] on first access.
Q2: How would you add cache invalidation when a dependency changes?
Record dependency values alongside the cache; on __get__, compare current values and recompute on mismatch. Alternatively, expose an explicit invalidate method or clear entries via __delete__.
Q3: Why do ORM fields work as class attributes but store per-instance data?
The field object is the shared descriptor carrying metadata; __set__ writes the value to a private attribute on each instance, separating behavior from state.
Q4: How do descriptors interact with inheritance?
Subclasses inherit the descriptor through the MRO, so validation and storage logic apply unchanged; cached instance state does not leak between instances of different classes.
Q5: What breaks when a descriptor is used on a class with __slots__?
getattr-based storage against obj.__dict__ fails because slotted instances have no dictionary. The descriptor must use declared slots or an external WeakKeyDictionary.
Key Takeaways
- Descriptors shine when field-level logic repeats across many classes
- Validated fields intercept __set__, normalize, and raise with the field name
- Cached properties store results on the instance, never on the shared descriptor
- ORM columns and environment-backed config fields are the same mechanism at framework scale
- Design for extension: defaults, TTL, slots support, and thread safety are the usual follow-ups
- Knowing descriptors explains why pydantic, attrs, Django fields, and SQLAlchemy columns work