Descriptors: secret weapon of frameworks

Track:
Python Core

The descriptor protocol is an obscure feature widely used by frameworks to link Python classes to database tables, JSON payloads, and dynamic forms. Understand this secret weapon and wield it wisely!

Most Python frameworks that use Python class syntax to specify structures with typed fields implement descriptor classes, which provide '__get__', '__set__' and '__delete__' method to enforce rules and perform conversions when the fields are read, updated, or deleted. Standard Python classes themselves depend of the descriptor protocol: that's what makes a function acessed via a class or object behave as a method.

I worked with Django for about an year before realizing that model and form fiend declarations were actually descriptors: specialized classes with '__get__' and '__set__' methods to handle conversion from Python attributes to SQL or HTML fields. Studying descriptors led me to a better understanding of Python classes work in general, and made it easier for me to debug Django issues, learn new frameworks and solve new problems with them.