Saturday 3:15 p.m.–3:45 p.m.
- Audience level:
- Python Core (language, stdlib, etc.)
The Python library uses descriptors frequently, but most developers overlook this feature. This talk will cover what a descriptor is, the current uses in the standard library, and how custom descriptors can be used in a developer’s toolset to eliminate repeated code.
#### Introduction Python developers often seem apprehensive about descriptors. This talk aims to remove some of the fear surrounding writing custom descriptors. #### Definition A [descriptor](https://docs.python.org/3/howto/descriptor.html) is a class that allows the programmer to define how given attributes are accessed and modified on an object. They define one or more of the methods `__get__`, `__set__`, or `__del__`. This allows the user to specify how attributes are declared and used with a greater deal of precision than a standard attribute declaration on an object. #### Common Examples Some relatively common examples of descriptors used in Python include decorators such as `@property` and `@classmethod`, which serve as a shorthand for relatively simple descriptors. Database Object Relational Mappers (ORMs) that interface with Python, such as used with Django, often take advantage of descriptors to simplify the declaration of attributes and control the data types being stored, which would otherwise be tedious given Python’s duck typing. Ever get a read-only property error? This is often the side effect of a descriptor with a `__get__` method defined but no `__set__` method defined. #### Making your own custom descriptors to simplify code With descriptors, Python developers can have greater control of code with less repetition. It is important to avoid circular loops which can occur when getting or setting attributes within the `__get__` or` __set__` variables within Python. And in case anything goes wrong, the appropriate Exceptions should be used to ease use and allow for debugging.