-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache_method.py
More file actions
62 lines (42 loc) · 1.04 KB
/
cache_method.py
File metadata and controls
62 lines (42 loc) · 1.04 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from dataclasses import dataclass
import functools
import itertools
COUNT = itertools.count(1)
class Class:
@functools.cache
def count(self):
return next(COUNT)
class LruClass:
@functools.lru_cache(maxsize=None)
def count(self):
return next(COUNT)
@dataclass(frozen=True)
class CachedProperty:
def count(self):
return self._count
@functools.cached_property
def _count(self):
return next(COUNT)
def test_ok(cls):
a, b = cls(), cls()
print(f'ok: {a.count()=} {b.count()=}')
assert a.count() + 1 == b.count()
test_ok(Class)
test_ok(LruClass)
test_ok(CachedProperty)
@dataclass(frozen=True, eq=False)
class Cache:
@functools.cache
def count(self):
return next(COUNT)
@dataclass(frozen=True, eq=False)
class Lru:
@functools.lru_cache(maxsize=None)
def count(self):
return next(COUNT)
def test_fails(cls):
a, b = cls(), cls()
print(f'FAIL: {a.count()=} {b.count()=}')
assert a.count() == b.count()
test_fails(Cache)
test_fails(Lru)