Build a TypeChecked Descriptor with __set_name__
Advanced · Write the code · from Python Descriptors: The Secret Behind @property and ORM Fields
From the lesson: Python Descriptors: The Secret Behind @property and ORM Fields
When you use @property in Python, something interesting happens behind the scenes. The attribute doesn't just sit there waiting to be read - it intercepts access and runs custom code. How does that work?
Read the lessonCreate a descriptor TypeChecked that:
1. Accepts an expected_type in __init__
2. Uses __set_name__ to learn its attribute name automatically
3. Raises TypeError with '{name} must be {type_name}' on invalid assignment
Use it in a Config class with host (str) and port (int). Set host='localhost' and port=8080, then print them.
class TypeChecked:
# Your code here
pass
class Config:
host = TypeChecked(str)
port = TypeChecked(int)
# Create Config, set host and port, print them
More Descriptor exercises
- Build a Simple DescriptorAdvanced
- Predict the Descriptor OutputAdvanced
- Fix the Shared State BugAdvanced
- Build a Cached Property DescriptorAdvanced
- Build a Range-Validated DescriptorAdvanced
All Python exercises · 50 practice problems · Metaprogramming quiz