Validated Attributes with Descriptors

medium
Unit 19 · Rate Limiting0/3 to milestone

Descriptors are what power @property, Django model fields and dataclass-style validation. Build reusable validated fields.

Implement:

  • a descriptor Field(type_, *, min=None, max=None, choices=None, default=MISSING) that validates on assignment. Raise TypeError for the wrong type (an int is acceptable where float is expected; bool is not acceptable as a number), and ValueError for out-of-range or not-in-choices values. Error messages must include the attribute name, so use __set_name__.
  • Reading a field that was never set returns default, or raises AttributeError if there's no default.
  • Values are stored per instance (two objects mustn't share values).
  • a class decorator @validated that adds an __init__(**kwargs) assigning each keyword to its field, and raising TypeError for unknown keywords.
#descriptors#classes#validation2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Validated Attributes with Descriptors · TechGradify