Editor

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 lesson

Create 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

All Python exercises · 50 practice problems · Metaprogramming quiz