Skip to Content
Clean Code in Python
book

Clean Code in Python

by Mariano Anaya
August 2018
Intermediate to advanced
332 pages
9h 12m
English
Packt Publishing
Content preview from Clean Code in Python

Using weak references

Another alternative (if we don't want to use __dict__) is to make the descriptor object keep track of the values for each instance itself, in an internal mapping, and return values from this mapping as well.

There is a caveat, though. This mapping cannot just be any dictionary. Since the client class has a reference to the descriptor, and now the descriptor will keep references to the objects that use it, this will create circular dependencies, and, as a result, these objects will never be garbage-collected because they are pointing at each other.

In order to address this, the dictionary has to be a weak key one, as defined in the weakref (WEAKREF 01) module.

In this case, the code for the descriptor might look like ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Clean Code in Python - Second Edition

Clean Code in Python - Second Edition

Mariano Anaya
Python for Programmers

Python for Programmers

Paul Deitel, Harvey Deitel

Publisher Resources

ISBN: 9781788835831Supplemental Content