© Jacob Zimmerman 2018
Jacob ZimmermanPython Descriptorshttps://doi.org/10.1007/978-1-4842-3727-4_9

9. Writing__delete__()

Jacob Zimmerman1 
(1)
New York, USA
 

This is going to be a short chapter, since there isn’t really all that much to say, but it didn’t really fit in any of the other chapters. Also, __get__() and __set__() sort of got their own chapters.

Most descriptor tutorials don’t even mention what to do with __delete__(), and they often don’t even have the method on their example descriptors.

If a descriptor is being used only internally (as opposed to being in a public library) and del is never called in the internal code, then there is no point in implementing a __delete__() method . But in a public library, there is no way to know whether or not users are going to use del on the descriptor attributes. Because of that, it is generally safest to include working __delete__() methods on data descriptors in a library. How those methods look depends on how the attributes are stored.

For internal storage, delete the entry from the dict:
del self.storage[instance]
For external storage, delete from the instance dictionary:
del vars(instance)[name]

If the descriptor doesn’t represent a stored value, do nothing. There’s truly very little variation in what __delete__() methods look like, other than the additional functionality a descriptor may have.

Summary

We’ve seen that __delete__() is a pretty simple method to implement, but deciding whether to actually implement it can be a difficult decision. In the end, though, it will be used so little that implementing it can probably be put off until it’s needed. The default behavior of raising an exception due to lack of implementation should get you by until then.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.232