Decorators and descriptors decoded | Tutorials
Python developers use decorators and descriptors on a daily basis, but many don't understand them well enough to create (or debug) them. Decorators are widely deployed in popular Python Web frameworks. Descriptors are the key to the database mappers used with those frameworks, but under the covers they play an even more crucial role in Python as the device that turns plain functions into bound methods, setting the value of the self argument. This tutorial is a gentle introduction these important language features, using a test-driven presentation and exercises, and covering enhancements in Python 3.6 that make class metaprogramming easier to get right.Decorators without closures are presented first, highlighting the difference between run time and import time that is crucial when meta-programming. We then get a firm grounding on closures and how they are implemented in Python, before moving to higher order function decorators and class decorators. Coverage of descriptors starts with a close look at Python's property built-in function and dynamic attribute look up. We then implement some ORM-like field validation descriptors, encounter a usability problem, and leverage PEP 487 -- Simpler customisation of class creation -- to solve it. Alternative implementations using a class decorator and a metaclass will be contrasted to the PEP 487 solution.
Luciano Ramalho
Luciano Ramalho is a Technical Principal at ThoughtWorks and the author of the bestselling book Fluent Python (O'Reilly, 2015). Since 1998 he has deployed Python on some of the largest Web sites in Brazil. His speaking record includes PyCon US, OSCON, OSCON-EU, PythonBrasil, RuPy and an ACM Webinar that was attended by more than 900 people. Ramalho is a fellow of the PSF and co-founder of the Brazilian Python Association and of Garoa Hacker Clube, the first hackerspace in Brazil.
Room 1
Wednesday, 17th May, 13:20 - 16:20