Lesson · Python Data Model & Special Methods
Descriptors
70 min readDescriptors
Descriptors control attribute behavior through `__get__`, `__set__`, and `__delete__`. Methods and properties rely on this protocol, so descriptors explain ordinary Python behavior as well as advanced frameworks.
Learning goals
- Explain what makes an object a descriptor: defining
__get__,__set__, or__delete__. - Trace how
Product.pricereachesPositive.__get__andPositive.__set__on reads and writes. - Write a validating descriptor that uses
__set_name__to learn its attribute name at class creation. - Distinguish data descriptors from non-data descriptors and say which one wins over instance attributes.
- Explain why ordinary methods and properties are descriptor-driven behavior.
Mental model
The order is the whole lesson. Positive is a data descriptor because it defines __set__, so every read and write of Product.price goes through its methods, and it keeps the actual number in the instance __dict__ under the name __set_name__ recorded. A non-data descriptor defines only __get__ (a function is the everyday case), so an instance attribute with the same name shadows it, which is the precedence question the fence shows as steps 1 to 4.
Four steps decide what `obj.attr` returns
data descriptors beat the instance dictionary
Mental model
the same mechanism as a compact list
obj.attr lookup order: 1. data descriptor on the class (defines __set__ or __delete__) 2. instance __dict__ (ordinary attribute values) 3. non-data descriptor or class attribute (functions and other __get__-only objects) 4. __getattr__ fallback (only if all of the above miss)
Core idea
Descriptors move attribute logic into small reusable objects: define __get__, __set__, or __delete__ and the class attribute controls what happens on reads, writes, and deletes of that name. The precedence rules do the routing: a data descriptor beats the instance dictionary, which is what lets Positive.__set__ validate every write to Product.price while __get__ reads the stored number back. The protocol also explains Python you have been using all along, because ordinary methods and properties are descriptor-driven behavior under different names.
Descriptor protocol
An object that defines __get__, __set__, or __delete__ can participate in descriptor-driven attribute access. Functions, methods, and properties are built on this mechanism.
__get__
__get__ answers reads: obj.attr calls it with the instance and the owner class, while Cls.attr calls it with obj=None. It should return the value the attribute represents, and the worked example reads the stored number from obj.__dict__[self.name] while returning the descriptor itself for class-level access. A function is a __get__ that returns a bound method for instances.
__set__
__set__ answers writes: obj.attr = value calls it with the instance and the incoming value, and it does not return anything. The worked example's Positive.__set__ rejects values at or below zero with ValueError before storing the number in obj.__dict__[self.name]. Defining __set__ is what makes a descriptor data, and data descriptors keep precedence over the instance dictionary.
__delete__
__delete__ answers del obj.attr, and defining it (like __set__) makes the descriptor a data descriptor. Implementations usually clear the stored value from the instance dictionary or raise AttributeError when the attribute cannot be deleted. The worked example does not implement it, so del product.price raises AttributeError.
Data vs non-data descriptors
A data descriptor defines __set__ or __delete__ and takes precedence over instance attributes. A non-data descriptor can be shadowed by an instance attribute.
Methods and properties as descriptor-driven behavior
Methods and properties are descriptor-driven behavior you already use: a function stored on a class defines __get__, so product.check hands back a bound method with the instance attached, and property is a data descriptor that routes reads to the getter and writes to the setter. Seeing them as descriptors explains the machinery behind ordinary attribute access and shows why the descriptor protocol appears throughout the standard library.
Walkthrough
Positive.__set_name__runs once when the class body is built, recording"price"on the descriptor so later calls know which key to use in the instance__dict__.Product.__init__assignsself.price = price, which is not a plain store: becausePositivedefines__set__, the assignment is routed toPositive.__set__, which rejects values at or below zero.print(Product(10).price)reads the attribute, andPositive.__get__receives the instance and returnsobj.__dict__["price"], the10written during__init__.- Predict before running: the printed line
10, whatProduct(0)does (raisesValueErrorfrom__set__), and whatProduct.pricereturns at class level.
Experiments to try
- Print
Product.priceandProduct(10).__dict__: the class attribute is thePositiveinstance, and the instance dictionary holds the actual number under the key"price". - Run
Product(0)andProduct(-5)and read theValueError; change the check to allow zero and confirm the boundary behavior moves. - Delete the
__set__method and rerun:Positivebecomes a non-data descriptor,self.price = pricewrites straight to the instance dictionary, and the validation stops running; explain why reads still return10. - Add
__delete__that removes the stored key and testdel product.pricebefore and after (fromAttributeErrorto a cleared dictionary).
Playable lesson
Lab: Descriptor and attribute lookup lab
Visualize data-descriptor lookup, instance dictionary lookup, non-data descriptor/class lookup, and __getattr__ fallback.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Descriptor and attribute lookup
answer to reveal which step winsLookup order
- 1. data descriptor on the class
- 2. instance __dict__
- 3. non-data descriptor or class attribute
- 4. __getattr__ fallback
Predict first
Why does `product.price` not read the instance dictionary directly?
`Positive` defines `__set__`, which makes it a data descriptor, so step 1 answers the read and `__get__` returns `obj.__dict__["price"]`.
Common mistakes
- Forgetting
__set_name__and hardcoding the attribute name inside the descriptor, so reusingPositivefor a second field makes both descriptors fight over one dictionary key. - Defining only
__get__and expecting validation on writes: a non-data descriptor loses to the instance dictionary, so plain assignment bypasses every check. - Writing
__get__that lets the stored key be missing without handling the miss, so reads of an unset attribute raiseKeyErrorinstead of theAttributeErrorcallers andhasattrexpect. - Reaching for a descriptor when one field needs a single check: a
propertyor validation in__init__is smaller, and descriptors earn their keep when the same field logic is reused across classes.
Practice: Easy
- Run the worked example and record
Product(10).price; then add aprintinside__set__and confirm it fires during__init__. - Run
Product(0)andProduct(-1)and record theValueError; identify the exact line that raises it. - Print
Product.priceandtype(Product.price); explain why class-level access returns the descriptor object.
Practice: Medium
- Add a second descriptor class
NonEmptyshaped likePositivefor anamefield on the same product; verify each descriptor stores under its own attribute name. - Compare a
Positive-style descriptor with apropertyperforming the same check on one field; list what each version reuses and what each costs. - Add
__delete__toPositivesodel product.priceremoves the stored key, then read the attribute again and decide which exception the read should raise.
Practice: Hard
- Design a
Bounded(minimum, maximum)descriptor that validates both ends and can be reused on two different classes; use__set_name__rather than hardcoded names and test both boundaries. - Build a failure lab: a descriptor without
__set__whose validation is bypassed by direct assignment; a descriptor with a hardcoded name that collides when reused; a__get__that raisesKeyErrorfor an unset attribute and thehasattrmisbehavior it causes. Explain each mechanism and the fix. - Connect this lesson to methods and properties: trace step by step what
product.priceand a method callproduct.check()each do through the descriptor protocol, and state wherepropertyand a function differ in the precedence order.
Lesson checklist
- I can name the three descriptor methods and which attribute operations call each.
- I can explain the lookup order: data descriptor, instance dictionary, non-data descriptor,
__getattr__fallback. - I can write a validating descriptor that uses
__set_name__to learn its attribute name. - I can say why a non-data descriptor loses to an instance attribute and what that means for validation.
Remember
Descriptors put attribute logic into reusable objects: define `__get__`, `__set__`, or `__delete__` and the class attribute takes over reads, writes, and deletes of that name. The worked example's `Positive` is a data descriptor that validates every write to `Product.price` and stores the number in the instance dictionary, which is also why precedence matters: with only `__get__` defined, plain assignment would shadow the descriptor and bypass the check.
Interview angles
What is the main purpose of **Descriptor protocol**?+
An object that defines __get__, __set__, or __delete__ can participate in descriptor-driven attribute access. Functions, methods, and properties are built on this mechanism.
What should you pay attention to when using **__get__**?+
__get__ answers reads: obj.attr calls it with the instance, and class-level access passes obj=None. The worked example reads the stored number from obj.__dict__[self.name] and returns the descriptor itself for class access; a function is a __get__ that returns a bound method.
How does **__set__** fit into this lesson?+
__set__ answers obj.attr = value, receives the instance and the incoming value, and returns nothing. Positive.__set__ rejects values at or below zero with ValueError before storing into obj.__dict__[self.name]; defining __set__ is what makes the descriptor data and gives it precedence over the instance dictionary.
Why does a descriptor that defines only `__get__` lose to a plain instance attribute?+
Only __set__ or __delete__ marks a descriptor as data, and data descriptors beat the instance dictionary. A __get__-only (non-data) descriptor is checked after the instance dictionary, so ordinary assignment shadows it and any validation inside the descriptor never runs.