Much of the usefulness of descriptors covered in this book was just using them as specialized properties. While this is one of the primary purposes of descriptors, it’s not all that they can do, though even the more innovative uses still largely serve that purpose.
SQLAlchemy4
This is probably the best-known library that uses descriptors for some of its stronger powers. (Probably; I did some digging and couldn’t find any hint of using descriptors, though the inheritance hierarchy is deep, so I gave up. If it doesn’t use descriptors, then I have absolutely no clue how it does what it does.) When using the declarative mapping style for data classes, the use of the Column descriptor allows users to specify all sorts of database metadata about the column that the attribute represents, including the data type, column name, whether it’s a primary key, etc.
That Column class also has a ton of other methods that are used when creating queries around the data, such as the ordering methods, __lt__(), __gt__(), etc. and what table it’s in.
Jigna
Jigna is a library that provides a kind of bridge between Python and JavaScript, allowing you to write Python code that creates web pages, including single-page applications. Using Trait descriptors, it can create two-way data bindings, generating AngularJS code that works with HTML pages.
The use is extremely innovative and powerful and it’s all thanks to descriptors that it can be as easy to use as it is.
For more information, visit its GitHub repository5 or check out the presentation the creator gave at EuroPython 20146.
Elk
Setting an attribute as required
Making lazy attributes
Delegating to the methods on the attribute
Making an attribute read-only
Creating constructors automatically
There are other features in the library attempting to make the tedious parts of class definition a little easier, and they can be seen in its documentation7.
Validators
This isn’t a specific instance of what’s out there, but rather a well-known use for descriptors. For example, if an attribute needs to be a string that follows a certain pattern, a descriptor can be created that takes the validator, and every time a value is set into the descriptor, it validates that the new value fits the validation.
There are a bunch of different validation descriptors that can be written that allow a class to maintain its invariants.
Summary
Now you’ve seen some really cool uses for descriptors. Also, this is the end of the book, so I suggest you go out there and make your own really awesome descriptors. Go and make the Python community an even more awesome place.