-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweakref_test.py
More file actions
34 lines (23 loc) · 837 Bytes
/
weakref_test.py
File metadata and controls
34 lines (23 loc) · 837 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"""Using `weakref` to create a cache."""
import gc
from weakref import WeakValueDictionary
import pytest
def test_weakref() -> None:
"""Use a `WeakValueDictionary` to cache large object."""
class BigImage:
"""Dummy class to simulate a large object."""
def __init__(self, value: int) -> None:
self.value = value
def __eq__(self, other: object) -> bool:
if not isinstance(other, BigImage):
return NotImplemented
return self.value == other.value
big_image = BigImage(10) # Create a reference
weak_dict = WeakValueDictionary()
weak_dict["big image"] = big_image
gc.collect()
assert weak_dict["big image"] is big_image
del big_image
gc.collect()
with pytest.raises(KeyError):
assert weak_dict["big image"]