Skip to main content

Python: Encapsulation with Descriptors

Luciano Ramalho (ThoughtWorks)
Average rating: ****.
(4.00, 3 ratings)
Slides:   1-PDF 

“This talk reveals the real meaning of the deceptively simple syntax of Django model classes, SQLAlchemy schemas and similar declarative APIs.

If you are new to Python, it is easy to overlook the descriptor mechanism, since it is not found in some other popular languages (but it is in modern JavaScript ).

This is a practical talk where new concepts are introduced when they are needed to solve a concrete problem.
Talk outline (times in minutes)

  1. (2’) Introduction, motivation and scenario
  2. (3’) Modelling a line item as a simple class with public attributes; adding getters and setters, Java style.
  3. (4’) The class is refactored to use properties to enforce business rules (for example, the quantity must be greater than zero). This works but introduces repetitive code.
  4. (7’) Repetition is removed by implementing custom descriptors. Overview of what is descriptor, UML diagram, relationship between descriptor instances and the managed class and managed attributes.
  5. (8’) Descriptor implementation details: where to store value of the managed attribute and how to generate a name for the target attribute. Initial problem solved.
  6. (4’) Limitations of the solution. The high (conceptual) cost of overcoming these limitations: class construction details.
  7. (9’) How a metaclass or a class decorator may help. Implementong a class decorator to provide finer control of the storage of the values in the managed instances.
Photo of Luciano Ramalho

Luciano Ramalho


Luciano Ramalho was a Web developer before the Netscape IPO in 1995, and switched from Perl to Java to Python in 1998. Since then he worked on some of the largest news portals in Brazil using Python, and taught Python web development in the Brazilian media, banking and government sectors. His speaking credentials include OSCON 2013 (slides) and 2002, two talks at PyCon USA 2013 and 17 talks over the years at PythonBrasil (the Brazilian PyCon), FISL (the largest FLOSS conference in the Southern Hemisphere) and a keynote at the RuPy Strongly Dynamic Conference in Brazil. Ramalho is a member of the Python Software Foundation and co-founder of Garoa Hacker Clube, the first hackerspace in Brazil. He is a managing partner at, a training company.