Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3b8cb17

Browse files
committed
#1061 (mainly by Thomas Wouters): use weak sets for abc caches.
1 parent b98dd2e commit 3b8cb17

4 files changed

Lines changed: 133 additions & 17 deletions

File tree

Doc/library/weakref.rst

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,23 +28,26 @@ it appears in a cache or mapping. For example, if you have a number of large
2828
binary image objects, you may wish to associate a name with each. If you used a
2929
Python dictionary to map names to images, or images to names, the image objects
3030
would remain alive just because they appeared as values or keys in the
31-
dictionaries. The :class:`WeakKeyDictionary` and :class:`WeakValueDictionary`
32-
classes supplied by the :mod:`weakref` module are an alternative, using weak
33-
references to construct mappings that don't keep objects alive solely because
34-
they appear in the mapping objects. If, for example, an image object is a value
35-
in a :class:`WeakValueDictionary`, then when the last remaining references to
36-
that image object are the weak references held by weak mappings, garbage
37-
collection can reclaim the object, and its corresponding entries in weak
38-
mappings are simply deleted.
31+
dictionaries. The :class:`WeakKeyDictionary`, :class:`WeakValueDictionary`
32+
and :class:`WeakSet` classes supplied by the :mod:`weakref` module are an
33+
alternative, using weak references to construct mappings that don't keep objects
34+
alive solely because they appear in the container objects.
35+
If, for example, an image object is a value in a :class:`WeakValueDictionary`,
36+
then when the last remaining references to that image object are the weak
37+
references held by weak mappings, garbage collection can reclaim the object,
38+
and its corresponding entries in weak mappings are simply deleted.
3939

4040
:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
4141
in their implementation, setting up callback functions on the weak references
4242
that notify the weak dictionaries when a key or value has been reclaimed by
43-
garbage collection. Most programs should find that using one of these weak
44-
dictionary types is all they need -- it's not usually necessary to create your
45-
own weak references directly. The low-level machinery used by the weak
46-
dictionary implementations is exposed by the :mod:`weakref` module for the
47-
benefit of advanced uses.
43+
garbage collection. :class:`WeakSet` implements the :class:`set` interface,
44+
but keeps weak references to its elements, just like a
45+
:class:`WeakKeyDictionary` does.
46+
47+
Most programs should find that using one of these weak container types is all
48+
they need -- it's not usually necessary to create your own weak references
49+
directly. The low-level machinery used by the weak dictionary implementations
50+
is exposed by the :mod:`weakref` module for the benefit of advanced uses.
4851

4952
Not all objects can be weakly referenced; those objects which can include class
5053
instances, functions written in Python (but not in C), methods (both bound and
@@ -179,6 +182,12 @@ methods of :class:`WeakKeyDictionary` objects.
179182
Return a list of weak references to the values.
180183

181184

185+
.. class:: WeakSet([elements])
186+
187+
Set class that keeps weak references to its elements. An element will be
188+
discarded when no strong reference to it exists any more.
189+
190+
182191
.. data:: ReferenceType
183192

184193
The type object for weak references objects.

Lib/abc.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
"""Abstract Base Classes (ABCs) according to PEP 3119."""
55

6+
from weakref import WeakSet
67

78
def abstractmethod(funcobj):
89
"""A decorator indicating abstract methods.
@@ -130,9 +131,9 @@ def __new__(mcls, name, bases, namespace):
130131
abstracts.add(name)
131132
cls.__abstractmethods__ = abstracts
132133
# Set up inheritance registry
133-
cls._abc_registry = set()
134-
cls._abc_cache = set()
135-
cls._abc_negative_cache = set()
134+
cls._abc_registry = WeakSet()
135+
cls._abc_cache = WeakSet()
136+
cls._abc_negative_cache = WeakSet()
136137
cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
137138
return cls
138139

@@ -172,7 +173,7 @@ def __subclasscheck__(cls, subclass):
172173
# Check negative cache; may have to invalidate
173174
if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter:
174175
# Invalidate the negative cache
175-
cls._abc_negative_cache = set()
176+
cls._abc_negative_cache = WeakSet()
176177
cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter
177178
elif subclass in cls._abc_negative_cache:
178179
return False

Lib/weakref.py

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,3 +337,108 @@ def update(self, dict=None, **kwargs):
337337
d[ref(key, self._remove)] = value
338338
if len(kwargs):
339339
self.update(kwargs)
340+
341+
342+
class WeakSet:
343+
def __init__(self, data=None):
344+
self.data = set()
345+
def _remove(item, selfref=ref(self)):
346+
self = selfref()
347+
if self is not None:
348+
self.data.discard(item)
349+
self._remove = _remove
350+
if data is not None:
351+
self.update(data)
352+
353+
def __iter__(self):
354+
for itemref in self.data:
355+
item = itemref()
356+
if item is not None:
357+
yield item
358+
359+
def __contains__(self, item):
360+
return ref(item) in self.data
361+
362+
def __reduce__(self):
363+
return (self.__class__, (list(self),),
364+
getattr(self, '__dict__', None))
365+
366+
def add(self, item):
367+
self.data.add(ref(item, self._remove))
368+
369+
def clear(self):
370+
self.data.clear()
371+
372+
def copy(self):
373+
return self.__class__(self)
374+
375+
def pop(self):
376+
while True:
377+
itemref = self.data.pop()
378+
item = itemref()
379+
if item is not None:
380+
return item
381+
382+
def remove(self, item):
383+
self.data.remove(ref(item))
384+
385+
def discard(self, item):
386+
self.data.discard(ref(item))
387+
388+
def update(self, other):
389+
if isinstance(other, self.__class__):
390+
self.data.update(other.data)
391+
else:
392+
for element in other:
393+
self.add(element)
394+
__ior__ = update
395+
396+
# Helper functions for simple delegating methods.
397+
def _apply(self, other, method):
398+
if not isinstance(other, self.__class__):
399+
other = self.__class__(other)
400+
newdata = method(other.data)
401+
newset = self.__class__()
402+
newset.data = newdata
403+
return newset
404+
405+
def _apply_mutate(self, other, method):
406+
if not isinstance(other, self.__class__):
407+
other = self.__class__(other)
408+
method(other)
409+
410+
def difference(self, other):
411+
return self._apply(other, self.data.difference)
412+
__sub__ = difference
413+
414+
def difference_update(self, other):
415+
self._apply_mutate(self, self.data.difference_update)
416+
__isub__ = difference_update
417+
418+
def intersection(self, other):
419+
return self._apply(other, self.data.intersection)
420+
__and__ = intersection
421+
422+
def intersection_update(self, other):
423+
self._apply_mutate(self, self.data.intersection_update)
424+
__iand__ = intersection_update
425+
426+
def issubset(self, other):
427+
return self.data.issubset(ref(item) for item in other)
428+
__lt__ = issubset
429+
430+
def issuperset(self, other):
431+
return self.data.issuperset(ref(item) for item in other)
432+
__gt__ = issuperset
433+
434+
def symmetric_difference(self, other):
435+
return self._apply(other, self.data.symmetric_difference)
436+
__xor__ = symmetric_difference
437+
438+
def symmetric_difference_update(self, other):
439+
self._apply_mutate(other, self.data.symmetric_difference_update)
440+
__ixor__ = symmetric_difference_update
441+
442+
def union(self, other):
443+
self._apply_mutate(other, self.data.union)
444+
__or__ = union

Modules/Setup.dist

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ pwd pwdmodule.c # this is needed to find out the user's home dir
116116
_sre _sre.c # Fredrik Lundh's new regular expressions
117117
_codecs _codecsmodule.c # access to the builtin codecs and codec registry
118118
_fileio _fileio.c # Standard I/O baseline
119+
_weakref _weakref.c # weak references
119120

120121
# The zipimport module is always imported at startup. Having it as a
121122
# builtin module avoids some bootstrapping problems and reduces overhead.

0 commit comments

Comments
 (0)