Different Forms of Implementing Descriptors
Understand the challenges related to shared state in Python descriptors and explore multiple implementation techniques. Learn why storing attribute data in the instance's __dict__ is common practice and examine alternatives like weak references. This lesson equips you with practical knowledge to implement descriptors while avoiding common pitfalls related to state management across class instances.
We'll cover the following...
We first have to understand a common issue that's specific to the nature of descriptors before thinking of ways of implementing them. First, we'll discuss the problem of a global shared state, and afterward, we'll move on and look at different ways descriptors can be implemented while taking this into consideration.
The issue of shared state
As we have already mentioned, descriptors need to be set as class attributes in order to work. This should not be a problem most of the time, but it does come with some warnings that need to be taken into consideration.
The problem with class attributes is that they are shared across all instances of that class. Descriptors are not an exception here, so if we try to keep data in a descriptor object, keep in mind that all of them will have access to the same value.
Let's see what happens when we incorrectly define a descriptor ...