@@ -8,29 +8,40 @@ def __init__(self, value):
8
8
self .value = value
9
9
10
10
@cache_per_thread ("value" )
11
- def compute (self , x ):
11
+ @property
12
+ def double_the_value (self ):
13
+ return self .value * 2
14
+
15
+ @cache_per_thread ("value" )
16
+ def add_to_value (self , x ):
12
17
return self .value + x
13
18
14
19
20
+ def test_cache_per_thread_property ():
21
+ obj = DummyClass (10 )
22
+ assert obj .double_the_value == 20 # First call, computes the result
23
+ assert obj .double_the_value == 20 # Cached result, no recomputation
24
+
25
+
15
26
def test_cache_per_thread_single_thread ():
16
27
obj = DummyClass (10 )
17
- assert obj .compute (5 ) == 15 # First call, computes the result
18
- assert obj .compute (5 ) == 15 # Cached result, no recomputation
28
+ assert obj .add_to_value (5 ) == 15 # First call, computes the result
29
+ assert obj .add_to_value (5 ) == 15 # Cached result, no recomputation
19
30
20
31
21
32
def test_cache_per_thread_different_args ():
22
33
obj = DummyClass (10 )
23
- assert obj .compute (5 ) == 15 # First call with x=5
24
- assert obj .compute (3 ) == 13 # First call with x=3
25
- assert obj .compute (5 ) == 15 # Cached result for x=5
34
+ assert obj .add_to_value (5 ) == 15 # First call with x=5
35
+ assert obj .add_to_value (3 ) == 13 # First call with x=3
36
+ assert obj .add_to_value (5 ) == 15 # Cached result for x=5
26
37
27
38
28
39
def test_cache_per_thread_different_threads ():
29
40
obj = DummyClass (300 ) # must be > 256 to avoid Python integer interning
30
41
results = []
31
42
32
43
def thread_func (x ):
33
- results .append (obj .compute (x ))
44
+ results .append (obj .add_to_value (x ))
34
45
35
46
thread1 = Thread (target = thread_func , args = (5 ,))
36
47
thread2 = Thread (target = thread_func , args = (5 ,))
@@ -50,7 +61,16 @@ def thread_func(x):
50
61
51
62
def test_cache_invalidation ():
52
63
obj = DummyClass (10 )
53
- assert obj .compute (5 ) == 15 # First call, computes the result
54
- assert obj .compute (5 ) == 15 # Cached result, no recomputation
64
+ assert obj .add_to_value (5 ) == 15 # First call, computes the result
65
+ assert obj .add_to_value (5 ) == 15 # Cached result, no recomputation
55
66
obj .value = 20 # Invalidate cache by changing the invalidator attribute
56
- assert obj .compute (5 ) == 25 # Recomputes the result
67
+ assert obj .add_to_value (5 ) == 25 # Recomputes the result
68
+
69
+
70
+ def test_cache_per_thread_on_plain_function ():
71
+ @cache_per_thread ()
72
+ def compute (x ):
73
+ return 42 + x
74
+
75
+ assert compute (5 ) == 47 # First call, computes the result
76
+ assert compute (5 ) == 47 # Cached result, no recomputation
0 commit comments