Descriptors and attribute lookup
Understand the mechanism behind properties and managed attributes.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Explain a reusable attribute rule
- Apply separate descriptor state from instance state
- Reason about use the simplest managed api
A reusable attribute rule
A descriptor is an object stored on a class that controls attribute reads, writes or deletion. It can reuse one attribute rule across several fields or classes.
Understand first
When several fields need the same managed behavior, copying properties can repeat the rule. A descriptor can package that rule once. Begin with ordinary attributes and properties; descriptors are optional machinery for reuse.
Words you will see
- Descriptor
- An object whose type defines __get__, __set__ or __delete__ for managed attribute access.
- Owner
- The class on which the descriptor is installed.
- __set_name__
- A class-creation hook that tells a descriptor its owner and chosen attribute name.
Place the rule on the class
title = UpperText() creates one descriptor in the Card class body. During class creation, __set_name__ receives Card and title, so storage becomes _title. Creating a descriptor inside Card.__init__ instead would create an ordinary instance attribute, not activate the same mechanism.
card.title = value calls __set__ with card as instance; it stores raw text on card._title. Reading card.title calls __get__, which reads and uppercases that stored text. The original value remains study, so this is a display rule rather than input normalization.
Handle class access deliberately
Card.title calls __get__ with instance=None. Returning self makes inspection possible without trying to read one nonexistent card's storage. The final isinstance therefore reports True.
This small example assumes string inputs and initialized storage. A nonstring can fail at upper() and an uninitialized read raises AttributeError. Define stricter validation or missing-value behavior if the public contract needs it. Prefer one property for one managed field; reuse a descriptor when that complexity pays for itself.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
title = UpperText()Install the shared rule on the owner class.
self.storage = "_" + nameDerive a backing name when Card is created.
setattr(instance, self.storage, value)Store data on the receiving card.
return getattr(instance, self.storage).upper()Transform the displayed read without overwriting raw storage.
A descriptor implements __get__, __set__ or __delete__ on an object stored as a class attribute. It can reuse validation across several owner classes. A property is a familiar built-in descriptor, so begin there before writing a custom one.
Conceptual shared rule versus per-owner data; not a measured heap view
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Install onceCard.title → one UpperText descriptor storing the backing-name rule _title.
- Write per cardThe descriptor receives the target instance and writes that card's _title, not its own shared value.
- Read per cardThe same descriptor reads the supplied card and uppercases only that card's stored text.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Assign after construction.
Try: Add card.title = "practice" before the prints.
The public read is PRACTICE while the backing read is practice.
Add a second owner instance.
Try: Create other = Card("code") and print card.title and other.title.
The values are independently STUDY and CODE.
Before you move on
If a second Card('code') is created, should the first card start showing CODE?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The descriptor shares its rule, not each card's value. Each card has its own _title and the first still displays STUDY.
Separate descriptor state from instance state
Descriptor state should describe the rule, while each owner instance holds its own managed values.
Understand first
Reusing validation across left and right is useful only if neither field overwrites the other. The storage-name rule and the owner instance together determine where a value lives.
Words you will see
- Per-instance storage
- State held on the specific owner instance rather than on the shared descriptor.
- Backing name
- The attribute name used internally for one managed field.
- Descriptor instance
- One reusable rule object; normally create a separate one for each declared field.
Separate two axes of independence
Pair.left and Pair.right are distinct NonBlank objects. __set_name__ sets _left on one and _right on the other. For each write, the instance argument chooses first or second, and storage chooses left or right.
The setter strips whitespace into a local variable, checks for a nonempty result and writes only the accepted text. After first.left is assigned E, first.right remains B and both second values remain C and D.
Avoid shared-name accidents
Do not reuse one descriptor object as both left and right with this simple implementation. The last __set_name__ would replace its storage name, making both names target the same backing attribute. Reuse the descriptor class, not the same object.
If input is blank, ValueError occurs before storage is changed. This rule assumes string input; explicit type validation belongs before strip when other values are permitted to reach the boundary. Trimming a string of length m takes work proportional to m in the worst case; the descriptor does not make it free.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
left = NonBlank()Create a rule object for the left field.
right = NonBlank()Create a different rule object for right.
cleaned = value.strip()Compute normalized text before validating.
first.left = " E "Write first._left without touching the other three values.
The descriptor object is shared by instances. Store each owner's value on that owner, not in one shared descriptor field. __set_name__ can discover the attribute name chosen in the class body.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Reject blank text explicitly.
Try: Append first.right = " ".
ValueError is visible and the accepted B value is not replaced.
Reveal a shared descriptor mistake.
Try: Use one rule = NonBlank() and assign both left = rule and right = rule in Pair.
The final name registration makes the fields collide, showing why separate descriptor objects matter.
Before you move on
If first.right = ' ' fails, what is first.right afterward?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
B. The cleaned string is empty, so the setter raises before replacing first._right. The other fields are unaffected too.
A nonnegative managed attribute
A data descriptor can validate a nonnegative quantity on every write while storing each order's accepted value on that order.
Understand first
The original NonNegative example demonstrates the core ownership boundary. The class holds one reusable rule; each order holds its own quantity. No network, file or framework is involved.
Words you will see
- Data descriptor
- A descriptor with a write or delete hook, which takes precedence over same-named instance dictionary entries.
- Managed write
- An attribute assignment routed through descriptor logic.
- Class access
- Reading the attribute through its owner class rather than a particular instance.
Read the entire handoff
__set_name__ derives _quantity from quantity. Order.__init__ assigns self.quantity, invoking NonNegative.__set__. The setter compares the input against zero and writes it with setattr only if accepted.
Order(3).quantity reads through __get__, which uses getattr on that specific order. instance is None occurs for Order.quantity, not for this normal instance read. Returning self for that case lets callers inspect the rule object.
A rule has a scope, not magic completeness
The comparison rejects negative values and permits zero. It does not reject bool or enforce an exact integer type; changing the domain to inventory counts would require a more specific policy. A missing _quantity would produce AttributeError rather than an invented zero.
Because __set__ exists, a raw instance dictionary entry named quantity cannot shadow this managed read under ordinary lookup. That precedence helps preserve the public API, but direct _quantity writes can still bypass the convention. Recap: descriptor reuse does not remove the need for precise input and ownership contracts.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
quantity = NonNegative()Install the rule on Order.
self.storage = '_' + nameChoose _quantity during class creation.
self.quantity = quantityInvoke the setter during initialization.
print(Order(3).quantity)Read three from the newly created order's backing storage.
The shared descriptor stores a storage-name rule; each Order stores its own quantity value. Class-level access returns the descriptor instead of reading one instance's state.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Test the lower boundary.
Try: Change Order(3) to Order(0).
It prints 0 because the check is strictly less than zero.
Test a later write.
Try: Create order = Order(3), then order.quantity = 5 and print(order.quantity).
The later assignment passes through the same validation and prints 5.
Before you move on
What would Order(0).quantity return, and what would Order(-1) do?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
The zero order returns 0. The negative order raises ValueError during initialization before a valid quantity is stored.
Where this idea earns its place
A descriptor centralises an attribute rule reused across owner classes. Properties are the common entry point; custom descriptors become useful when several fields need consistent validation or access behaviour. Keep the mechanism small enough that a reader can still determine where one instance's value actually lives.
Follow the mechanism step by step
The descriptor object is stored on the class and is therefore shared. __set_name__ learns the declared attribute name; __get__ handles access and __set__ can validate assignment. Store per-instance data on the instance or another explicitly keyed store, not in a single descriptor value field shared by every owner.
Work through a concrete application
Trace two Order objects with different quantities. Setting one quantity should not change the other. On class-level access, instance is None and the example returns the descriptor itself. On instance access, it reads the chosen storage attribute. State what happens when the value has not yet been initialized.
Failure cases and misleading shortcuts
Data descriptors defining a set/delete operation take precedence over a same-named entry in an instance dictionary. Non-data descriptors can be shadowed. Accidentally sharing one storage name across fields, reusing a descriptor under incompatible names or forgetting class access can create subtle framework-like bugs.
Cost, ownership and alternatives
A property may be easier for one isolated rule, while a descriptor reduces duplication across many managed attributes. Validation and backing storage still have costs and ownership requirements. Weak-key storage can avoid retaining owners but introduces hashability and lifetime constraints that an instance attribute may not need.
Verify the contract
Test two owners, two managed fields, valid and invalid assignments, class access and missing initialization. Confirm the rule rejects invalid state instead of silently clamping it. Include a test showing whether direct backing-field mutation is outside the public contract; Python conventions alone are not authorization barriers.
Transfer question: Why is storing self.value in a descriptor often wrong for per-object data?
The descriptor's self is the one class-level descriptor, not the owner instance. Every owner would then read the same value. Store state on the supplied instance or in a deliberately keyed mapping and test owner isolation.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: A nonnegative managed attribute
Without copying the worked code, reproduce its observable contract: The shared descriptor stores a storage-name rule; each Order stores its own quantity value. Class-level access returns the descriptor instead of reading one instance's state. Then change one boundary input and explain the result.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Reuse a nonnegative integer rule
Return an Order class with a data descriptor quantity. Every owner keeps its own exact nonnegative integer.
The contract
- Return a class Order with Order(quantity) and a class-installed quantity descriptor defining __get__, __set__ and __set_name__.
- Accept only exact int values at least zero, excluding bool, in construction and later assignment. Invalid values raise ValueError before mutation.
- Store values per instance; Order.quantity returns the descriptor. A conflicting quantity entry in __dict__ must not override its public read. Missing backing storage raises AttributeError.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Installed descriptor and value
O = build_order_class() d = O.__dict__["quantity"] o = O(3) assert isinstance(O, type) and O.quantity is d and callable(type(d).__get__) and callable(type(d).__set__) and callable(type(d).__set_name__) and type(o.quantity) is int and o.quantity == 3
- Zero boundary and later update
O = build_order_class() o = O(0) assert type(o.quantity) is int and o.quantity == 0 o.quantity = 8 assert type(o.quantity) is int and o.quantity == 8
- Invalid construction
O = build_order_class() for value in (-1, True, 2.0, "2", None): try: O(value) except ValueError: pass else: assert False, repr(value) o = O(2) assert type(o.quantity) is int and o.quantity == 2 - Rejected write preserves state
O = build_order_class() o = O(7) for value in (-2, False, "3"): try: o.quantity = value except ValueError: pass else: assert False, "invalid write accepted" assert type(o.quantity) is int and o.quantity == 7 - Owner isolation and precedence
O = build_order_class() a, b = O(2), O(9) a.quantity = 4 a.__dict__["quantity"] = 100 assert type(a.quantity) is int and a.quantity == 4 and type(b.quantity) is int and b.quantity == 9 and O.quantity is O.__dict__["quantity"]
- Required missing attribute
O = build_order_class() missing = object.__new__(O) try: missing.quantity except AttributeError: pass else: assert False, "missing required value invented" o = O(5) assert type(o.quantity) is int and o.quantity == 5 and O.quantity is O.__dict__["quantity"]
Why does the descriptor keep a backing name rather than one quantity value?
One descriptor serves many orders. Its name is reusable metadata, but each accepted quantity belongs on the supplied owner instance. The solution uses constant metadata per field and one value per owner; ordinary reads and writes add constant-size lookup and validation work.
Keep two reusable fields independent
Return a Pair class with left and right text descriptors. Normalize surrounding whitespace, reject blank values, and separate both fields on both owners.
The contract
- Pair(left, right) accepts strings. Each class field uses its own instance of one descriptor class with __set_name__, __get__ and __set__.
- Trim surrounding whitespace on each write, preserving internal spaces and case. Reject nonstrings or cleaned empty strings with ValueError before mutation.
- Class access returns the descriptor. Both fields and all Pair instances remain independent; do not share one backing value or one descriptor object across names.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Two installed rules
P = build_pair_class() a, b = P.__dict__["left"], P.__dict__["right"] p = P(" A ", " B ") assert a is not b and type(a) is type(b) and P.left is a and P.right is b and callable(type(a).__set_name__) and type(p.left) is str and p.left == "A" and type(p.right) is str and p.right == "B" - Internal spaces and case
P = build_pair_class() p = P(" Read Now ", "x") assert type(p.left) is str and p.left == "Read Now" and type(p.right) is str and p.right == "x" - Blank and nonstring rejection
P = build_pair_class() for value in ("", " \t ", None, 2): try: P(value, "ok") except ValueError: pass else: assert False, repr(value) p = P("a", "b") assert type(p.left) is str and p.left == "a" and type(p.right) is str and p.right == "b" - Failed field update
P = build_pair_class() p = P("a", "b") try: p.right = " " except ValueError: pass else: assert False, "blank update accepted" assert type(p.left) is str and p.left == "a" and type(p.right) is str and p.right == "b" - Names and owner isolation
P = build_pair_class() a, b = P("a", "b"), P("c", "d") a.left = " e " assert type(a.left) is str and a.left == "e" and a.right == "b" and type(b.left) is str and b.left == "c" and b.right == "d" - Repeated assignment and data precedence
P = build_pair_class() p = P("x", "x") p.left = " y " p.right = " z " p.__dict__["left"] = "bypass" assert type(p.left) is str and p.left == "y" and type(p.right) is str and p.right == "z" and P.left is P.__dict__["left"]
Why is reusing one descriptor object for left and right wrong here?
It holds one storage-name slot, so the second __set_name__ would replace the first name and both fields would collide. Separate rule objects share code without sharing names. A write to m-character text takes O(m) trimming work and may allocate O(m) text; each owner retains two strings.
Transfer: make absence and deletion meaningful
The requirement changes from a required count to an optional count: before assignment or after deletion it reads as zero, without creating stored state.
The contract
- Return class Draft() with class-installed count descriptor using __get__, __set__, __delete__ and __set_name__. Class access returns the rule.
- Missing count reads as exact int 0 without adding an instance key. Accept exact nonnegative ints; invalid writes raise ValueError and preserve accepted state.
- Deletion removes stored count and is allowed repeatedly, even on a fresh instance. Other owners are unaffected; a same-named public dictionary key cannot shadow the data descriptor.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Missing read has no write
D = build_draft_class() d = D() before = dict(d.__dict__) assert D.count is D.__dict__["count"] and callable(type(D.count).__set_name__) and callable(type(D.count).__delete__) and type(d.count) is int and d.count == 0 and d.__dict__ == before
- Explicit zero and positive write
D = build_draft_class() d = D() d.count = 0 assert type(d.count) is int and d.count == 0 d.count = 6 assert type(d.count) is int and d.count == 6
- Delete resets and removes
D = build_draft_class() d = D() before = dict(d.__dict__) d.count = 4 assert type(d.count) is int and d.count == 4 del d.count assert type(d.count) is int and d.count == 0 and d.__dict__ == before
- Repeated fresh deletion
D = build_draft_class() d = D() del d.count del d.count assert type(d.count) is int and d.count == 0 and d.__dict__ == {} and D.count is D.__dict__["count"] - Invalid update leaves value
D = build_draft_class() d = D() d.count = 7 for value in (-1, True, 1.0, "1", None): try: d.count = value except ValueError: pass else: assert False, repr(value) assert type(d.count) is int and d.count == 7 - Delete isolation and precedence
D = build_draft_class() a, b = D(), D() a.count, b.count = 2, 8 a.__dict__["count"] = 99 assert type(a.count) is int and a.count == 2 del a.count assert type(a.count) is int and a.count == 0 and type(b.count) is int and b.count == 8 and D.count is D.__dict__["count"]
How is zero after deletion different from zero after assignment?
The public value is equal, but deletion removes storage and a missing read supplies the documented default without writing. Keeping that distinction makes lifecycle behavior testable. The descriptor adds constant-size metadata and lookup work; each assigned owner holds its own integer.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneData versus non-data descriptors
A data descriptor wins over an instance dictionary entry. A non-data descriptor, which has a read hook but no write or delete hook, can be shadowed by such an entry.
Understand first
Optional depth: the phrase read-only rule is easy to misread. A descriptor with only __get__ does not block ordinary instance shadowing. Properties differ because the property type has data-descriptor behavior, even without a user-provided setter.
Words you will see
- Non-data descriptor
- A descriptor with __get__ but no __set__ or __delete__.
- Shadowing
- A nearer attribute value hiding another source during lookup.
- Data descriptor precedence
- Ordinary reads prefer a class data descriptor over an instance dictionary value.
Read from the winning source
For loose, the instance dictionary entry wins because ReadOnlyRule is a non-data descriptor. For strict, ManagedRule wins because its type defines __set__. Its getter returns managed and ignores the raw strict key.
The later sample.strict assignment calls __set__, storing accepted under saved. That separate key is read by the final print. A hook's existence determines descriptor category; whether the hook accepts or rejects a particular value is a separate choice.
Recognize where this appears
Ordinary Python functions on classes are non-data descriptors: they bind methods but can be shadowed on ordinary instances. A property is a data descriptor and cannot be bypassed by adding a same-named instance dictionary key.
These rules assume ordinary attribute lookup. A custom __getattribute__ can alter behavior and should not be introduced casually. Use this model to explain surprises, not to justify patching hidden internals in application code. A narrow, documented public attribute remains easier to test.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
loose = ReadOnlyRule()Install a non-data descriptor.
strict = ManagedRule()Install a descriptor whose type supplies a write hook.
sample.__dict__["strict"] = "instance"Add a conflicting instance entry that cannot win this read.
sample.strict = "accepted"Ordinary assignment invokes the managed setter.
A descriptor defining __set__ or __delete__ is a data descriptor and takes precedence over an instance dictionary entry. A non-data descriptor can be shadowed by an instance attribute. This ordering explains many apparently surprising attribute reads.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Remove a shadow.
Try: Delete sample.__dict__["loose"] before its print.
loose now reads rule from the descriptor.
Turn strict into a non-data descriptor.
Try: Remove ManagedRule.__set__ and the later strict assignment and saved print.
The strict instance dictionary entry wins and prints instance.
Before you move on
If the loose dictionary key is deleted, what does sample.loose return?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
rule. With the instance shadow removed, lookup reaches ReadOnlyRule.__get__ again.
Use the simplest managed API
A managed attribute must define what missing reads and deletion mean. A descriptor may reject them or give them a deliberate domain meaning.
Understand first
Optional depth: a reusable rule needs lifecycle semantics, not just one happy-path setter. An optional count can deliberately read as zero before assignment and after deletion. A required field might instead raise AttributeError.
Words you will see
- __delete__
- The descriptor hook for del instance.attribute.
- Missing-value policy
- The documented meaning of an attribute that has no stored value.
- Idempotent deletion
- Deleting more than once has the same final state as deleting once.
Define absence rather than guessing
getattr with default zero reads an absent backing attribute without inserting it. That is a chosen count policy, not a universal descriptor rule. Class access still returns self for inspection.
The setter accepts exact nonnegative ints and rejects bool. The delete hook pops the backing key with a default, so deleting an already absent count is allowed. Reading afterward returns zero because the backing value is absent again.
Choose a simpler API when possible
For one count field, a property or an explicit reset method may be easier for readers. A descriptor earns its complexity when the same lifecycle rule appears across many fields or owner types.
This implementation assumes owners have instance dictionaries and reserves the underscore backing name. Slotted owners need a storage strategy that works with their layout. It does not catch arbitrary exceptions or recover from corrupted backing state. Recap: reusable machinery should make absence and deletion more explicit, not hide failures.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
return getattr(instance, self.storage, 0)Read the chosen default without writing it.
draft.count = 4Store a valid explicit count on this draft.
instance.__dict__.pop(self.storage, None)Remove only this draft's backing entry.
del draft.countInvoke deletion so a subsequent read returns zero.
A custom descriptor can be appropriate for repeated validation or framework machinery, but it increases the amount a reader must know. Prefer a property or ordinary method for a one-off rule. Validate deletion and missing-value behaviour if the public contract permits them.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Delete twice.
Try: Repeat del draft.count before the final print.
It still prints zero because deletion is deliberately idempotent.
Try a bool.
Try: Replace draft.count = 4 with draft.count = True.
ValueError is visible before a backing value is stored.
Before you move on
Does reading a fresh draft.count create _count, and does deleting it twice fail?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
The read does not insert _count. Both deletions succeed because pop uses a default for absence. A later read still returns zero.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.