Skip to content

Commit

Permalink
Add functools.cached_property backport (#5031)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
maffoo authored Mar 1, 2022
1 parent d2ae1e4 commit 5ff22ce
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
6 changes: 6 additions & 0 deletions cirq-core/cirq/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@
import sympy.printing.repr


try:
from functools import cached_property # pylint: disable=unused-import
except ImportError:
from backports.cached_property import cached_property # type: ignore[no-redef]


def proper_repr(value: Any) -> str:
"""Overrides sympy and numpy returning repr strings that don't parse."""

Expand Down
18 changes: 18 additions & 0 deletions cirq-core/cirq/_compat_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import cirq.testing
from cirq._compat import (
block_overlapping_deprecation,
cached_property,
proper_repr,
dataclass_repr,
deprecated,
Expand Down Expand Up @@ -967,3 +968,20 @@ def f(x):

with cirq.testing.assert_deprecated('f', deadline='v1000.0', count=1):
f(5)


def test_cached_property():
class Foo:
def __init__(self):
self.bar_calls = 0

@cached_property
def bar(self):
self.bar_calls += 1
return []

foo = Foo()
bar = foo.bar
bar2 = foo.bar
assert bar2 is bar
assert foo.bar_calls == 1
3 changes: 3 additions & 0 deletions cirq-core/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
# for python 3.6 and below dataclasses needs to be installed
dataclasses; python_version < '3.7'

# functools.cached_property was introduced in python 3.8
backports.cached_property~=1.0.1; python_version < '3.8'

duet~=0.2.0
matplotlib~=3.0
networkx~=2.4
Expand Down

0 comments on commit 5ff22ce

Please sign in to comment.