Home > Articles > Open Source > Python

  • Print
  • + Share This
From the author of


Descriptors are a powerful and useful Python feature, especially when combined with class decorators. Although decorators are declared as class attributes, they're accessed as instance attributes; if we want to associate data with a descriptor, we must either compute that data when it's requested (as in the first example), or provide storage for it (for example, using a cache, as in the second example). If we want to store descriptor-related data in instances, we can do so by using a class decorator to create a data attribute to hold the data and a descriptor attribute to provide mediated access to the data, as the third example showed.

Like most of Python's advanced features, descriptors and class decorators are not the first tools to try when a problem needs to be solved. But they should always be kept in mind because, in the right circumstances, they can provide clean and elegant solutions that aren't easily achieved by other means.

For details on the techniques shown in this article (along with many other Python techniques), see my book Programming in Python 3: A Complete Introduction to the Python Language.

  • + Share This
  • 🔖 Save To Your Account