Skip to content

Commit 5ff22ce

Browse files
authored
Add functools.cached_property backport (#5031)
The [`@functools.cached_property`](https://docs.python.org/3/library/functools.html#functools.cached_property) decorator is really useful but not currently available in cirq since it was introduced in python 3.8 but we still support python 3.7. This adds `backports.cached_property` to make cached properties available in python 3.7, using import logic in `cirq._compat` to get it from the standard library or backport module, as needed.
1 parent d2ae1e4 commit 5ff22ce

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

cirq-core/cirq/_compat.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@
3131
import sympy.printing.repr
3232

3333

34+
try:
35+
from functools import cached_property # pylint: disable=unused-import
36+
except ImportError:
37+
from backports.cached_property import cached_property # type: ignore[no-redef]
38+
39+
3440
def proper_repr(value: Any) -> str:
3541
"""Overrides sympy and numpy returning repr strings that don't parse."""
3642

cirq-core/cirq/_compat_test.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import cirq.testing
3636
from cirq._compat import (
3737
block_overlapping_deprecation,
38+
cached_property,
3839
proper_repr,
3940
dataclass_repr,
4041
deprecated,
@@ -967,3 +968,20 @@ def f(x):
967968

968969
with cirq.testing.assert_deprecated('f', deadline='v1000.0', count=1):
969970
f(5)
971+
972+
973+
def test_cached_property():
974+
class Foo:
975+
def __init__(self):
976+
self.bar_calls = 0
977+
978+
@cached_property
979+
def bar(self):
980+
self.bar_calls += 1
981+
return []
982+
983+
foo = Foo()
984+
bar = foo.bar
985+
bar2 = foo.bar
986+
assert bar2 is bar
987+
assert foo.bar_calls == 1

cirq-core/requirements.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
# for python 3.6 and below dataclasses needs to be installed
44
dataclasses; python_version < '3.7'
55

6+
# functools.cached_property was introduced in python 3.8
7+
backports.cached_property~=1.0.1; python_version < '3.8'
8+
69
duet~=0.2.0
710
matplotlib~=3.0
811
networkx~=2.4

0 commit comments

Comments
 (0)