MCPcopy Index your code
hub / github.com/python/cpython / test_weak_keyed_cascading_deletes

Method test_weak_keyed_cascading_deletes

Lib/test/test_weakref.py:1897–1941  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

1895 self.assertRaises(TypeError, d.__setitem__, 13, 13)
1896
1897 def test_weak_keyed_cascading_deletes(self):
1898 # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
1899 # over the keys via self.data.iterkeys(). If things vanished from
1900 # the dict during this (or got added), that caused a RuntimeError.
1901
1902 d = weakref.WeakKeyDictionary()
1903 mutate = False
1904
1905 class C(object):
1906 def __init__(self, i):
1907 self.value = i
1908 def __hash__(self):
1909 return hash(self.value)
1910 def __eq__(self, other):
1911 if mutate:
1912 # Side effect that mutates the dict, by removing the
1913 # last strong reference to a key.
1914 del objs[-1]
1915 return self.value == other.value
1916
1917 objs = [C(i) for i in range(4)]
1918 for o in objs:
1919 d[o] = o.value
1920 del o # now the only strong references to keys are in objs
1921 # Find the order in which iterkeys sees the keys.
1922 objs = list(d.keys())
1923 # Reverse it, so that the iteration implementation of __delitem__
1924 # has to keep looping to find the first object we delete.
1925 objs.reverse()
1926
1927 # Turn on mutation in C.__eq__. The first time through the loop,
1928 # under the iterkeys() business the first comparison will delete
1929 # the last item iterkeys() would see, and that causes a
1930 # RuntimeError: dictionary changed size during iteration
1931 # when the iterkeys() loop goes around to try comparing the next
1932 # key. After this was fixed, it just deletes the last object *our*
1933 # "for o in obj" loop would have gotten to.
1934 mutate = True
1935 count = 0
1936 for o in objs:
1937 count += 1
1938 del d[o]
1939 gc_collect() # For PyPy or other GCs.
1940 self.assertEqual(len(d), 0)
1941 self.assertEqual(count, 2)
1942
1943 def test_make_weak_valued_dict_repr(self):
1944 dict = weakref.WeakValueDictionary()

Callers

nothing calls this directly

Calls 6

keysMethod · 0.95
gc_collectFunction · 0.90
listClass · 0.85
CClass · 0.70
reverseMethod · 0.45
assertEqualMethod · 0.45

Tested by

no test coverage detected