Deviopath › Python

Validating Descriptor

Hard · Classes

A descriptor is an object stored on a class that controls an attribute through __get__ and __set__. When the class is created, Python calls the descriptor's __set_name__(owner, name), so it learns the attribute name. Model fields in Django and SQLAlchemy work this way.

Complete Bounded(low, high), a descriptor for whole numbers in a range:

- __set_name__ remembers the attribute name

- __set__ raises TypeError("<name> must be an int") when the value is not an int (a bool does not count as an int here), and ValueError("<name> must be between <low> and <high>") when it is out of range (both ends included)

- __get__ returns the value stored for that instance. When it is called on the class itself, obj is None: return the descriptor.

Store values per instance (for example in obj.__dict__), not on the descriptor: one descriptor object is shared by every instance of the class.

The driver run_cart_lines(ops) is already written. It creates CartLine objects (quantity from 1 to 1000, discount from 0 to 100), sets and reads attributes, and logs results and error messages.

Next: Event Emitter with once()