Skip to content

Commit

Permalink
Remove cached_property backport (quantumlib#6398)
Browse files Browse the repository at this point in the history
We require recent-enough Python which has `functools.cached_property`.

Fixes quantumlib#6395
  • Loading branch information
Josha91 authored Jan 11, 2024
1 parent 4d35768 commit 968ed4c
Show file tree
Hide file tree
Showing 35 changed files with 52 additions and 69 deletions.
6 changes: 0 additions & 6 deletions cirq-core/cirq/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,6 @@ def with_debug(value: bool) -> Iterator[None]:
__cirq_debug__.reset(token)


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


# Sentinel used by wrapped_no_args below when method has not yet been cached.
_NOT_FOUND = object()

Expand Down
18 changes: 0 additions & 18 deletions cirq-core/cirq/_compat_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
from cirq._compat import (
block_overlapping_deprecation,
cached_method,
cached_property,
proper_repr,
dataclass_repr,
deprecated,
Expand Down Expand Up @@ -1011,23 +1010,6 @@ def f(x):
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


class Bar:
def __init__(self) -> None:
self.foo_calls: Dict[int, int] = collections.Counter()
Expand Down
3 changes: 2 additions & 1 deletion cirq-core/cirq/circuits/circuit_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
component operations in order, including any nested CircuitOperations.
"""
import math
from functools import cached_property
from typing import (
Callable,
cast,
Expand All @@ -38,7 +39,7 @@
import sympy

from cirq import circuits, ops, protocols, value, study
from cirq._compat import cached_property, proper_repr
from cirq._compat import proper_repr

if TYPE_CHECKING:
import cirq
Expand Down
5 changes: 3 additions & 2 deletions cirq-core/cirq/circuits/frozen_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""An immutable version of the Circuit data structure."""
from functools import cached_property
from typing import (
AbstractSet,
FrozenSet,
Expand Down Expand Up @@ -90,7 +91,7 @@ def tags(self) -> Tuple[Hashable, ...]:
"""Returns a tuple of the Circuit's tags."""
return self._tags

@_compat.cached_property
@cached_property
def untagged(self) -> 'cirq.FrozenCircuit':
"""Returns the underlying FrozenCircuit without any tags."""
return self._from_moments(self._moments) if self.tags else self
Expand Down Expand Up @@ -148,7 +149,7 @@ def _is_measurement_(self) -> bool:
def all_qubits(self) -> FrozenSet['cirq.Qid']:
return super().all_qubits()

@_compat.cached_property
@cached_property
def _all_operations(self) -> Tuple['cirq.Operation', ...]:
return tuple(super().all_operations())

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@

import abc
from dataclasses import dataclass, field
from functools import cached_property
from typing import Dict, TYPE_CHECKING, List, Set, Type

from cirq import _compat, ops, devices
from cirq import ops, devices
from cirq.devices import noise_utils

if TYPE_CHECKING:
Expand Down Expand Up @@ -131,7 +132,7 @@ def _get_pauli_error(self, p_error: float, op_id: noise_utils.OpIdentifier):
p_error -= noise_utils.decoherence_pauli_error(self.t1_ns[q], self.tphi_ns[q], time_ns)
return p_error

@_compat.cached_property
@cached_property
def _depolarizing_error(self) -> Dict[noise_utils.OpIdentifier, float]:
"""Returns the portion of Pauli error from depolarization."""
depol_errors = {}
Expand Down
12 changes: 6 additions & 6 deletions cirq-core/cirq/ops/clifford_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

from cirq import protocols, value, linalg, qis
from cirq._import import LazyLoader
from cirq._compat import cached_property, cached_method
from cirq._compat import cached_method
from cirq.ops import common_gates, named_qubit, raw_types, pauli_gates, phased_x_z_gate
from cirq.ops.pauli_gates import Pauli
from cirq.type_workarounds import NotImplementedType
Expand Down Expand Up @@ -693,7 +693,7 @@ def to_phased_xz_gate(self) -> phased_x_z_gate.PhasedXZGate:
"""
return self._to_phased_xz_gate

@cached_property
@functools.cached_property
def _to_phased_xz_gate(self) -> phased_x_z_gate.PhasedXZGate:
x_to_flip, z_to_flip = self.clifford_tableau.rs
flip_index = int(z_to_flip) * 2 + x_to_flip
Expand Down Expand Up @@ -792,7 +792,7 @@ def _has_unitary_(self) -> bool:
def _unitary_(self) -> np.ndarray:
return self._unitary

@cached_property
@functools.cached_property
def _unitary(self) -> np.ndarray:
mat = np.eye(2)
qubit = named_qubit.NamedQubit('arbitrary')
Expand All @@ -810,7 +810,7 @@ def decompose_gate(self) -> Sequence['cirq.Gate']:
"""
return self._decompose_gate

@cached_property
@functools.cached_property
def _decompose_gate(self) -> Sequence['cirq.Gate']:
if self == SingleQubitCliffordGate.H:
return [common_gates.H]
Expand All @@ -829,7 +829,7 @@ def decompose_rotation(self) -> Sequence[Tuple[Pauli, int]]:
"""
return self._decompose_rotation

@cached_property
@functools.cached_property
def _decompose_rotation(self) -> Sequence[Tuple[Pauli, int]]:
x_rot = self.pauli_tuple(pauli_gates.X)
y_rot = self.pauli_tuple(pauli_gates.Y)
Expand Down Expand Up @@ -926,7 +926,7 @@ def _circuit_diagram_info_(
def _value_equality_values_(self):
return self._value_equality_values

@cached_property
@functools.cached_property
def _value_equality_values(self):
return self._clifford_tableau.matrix().tobytes() + self._clifford_tableau.rs.tobytes()

Expand Down
7 changes: 4 additions & 3 deletions cirq-core/cirq/ops/control_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import abc
from functools import cached_property
from typing import Collection, Tuple, TYPE_CHECKING, Any, Dict, Iterator, Optional, Sequence, Union
import itertools

from cirq import protocols, value, _compat
from cirq import protocols, value

if TYPE_CHECKING:
import cirq
Expand Down Expand Up @@ -144,7 +145,7 @@ def __init__(self, data: Sequence[Union[int, Collection[int]]]):
(cv,) if isinstance(cv, int) else tuple(sorted(set(cv))) for cv in data
)

@_compat.cached_property
@cached_property
def is_trivial(self) -> bool:
return self._qubit_sums == ((1,),) * self._num_qubits_()

Expand Down Expand Up @@ -252,7 +253,7 @@ def __init__(self, data: Collection[Sequence[int]], *, name: Optional[str] = Non
if not all(len(p) == num_qubits for p in self._conjunctions):
raise ValueError(f'Each term of {self._conjunctions} should be of length {num_qubits}.')

@_compat.cached_property
@cached_property
def is_trivial(self) -> bool:
return self._conjunctions == ((1,) * self._num_qubits_(),)

Expand Down
3 changes: 2 additions & 1 deletion cirq-core/cirq/sim/state_vector_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"""Abstract classes for simulations which keep track of state vector."""

import abc
from functools import cached_property
from typing import Any, Dict, Iterator, Sequence, Type, TYPE_CHECKING, Generic, TypeVar

import numpy as np
Expand Down Expand Up @@ -121,7 +122,7 @@ def __init__(
qubit_map=final_simulator_state.qubit_map,
)

@_compat.cached_property
@cached_property
def final_state_vector(self) -> np.ndarray:
return self._get_merged_sim_state().target_tensor.reshape(-1)

Expand Down
2 changes: 1 addition & 1 deletion cirq-ft/cirq_ft/algos/and_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import cached_property
from typing import Sequence, Tuple

import numpy as np
from numpy.typing import NDArray

import attr
import cirq
from cirq._compat import cached_property
from cirq_ft import infra


Expand Down
2 changes: 1 addition & 1 deletion cirq-ft/cirq_ft/algos/apply_gate_to_lth_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import cached_property
import itertools
from typing import Callable, Sequence, Tuple

import attr
import cirq
import numpy as np
from cirq._compat import cached_property
from cirq_ft import infra
from cirq_ft.algos import unary_iteration_gate

Expand Down
2 changes: 1 addition & 1 deletion cirq-ft/cirq_ft/algos/arithmetic_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import cached_property
from typing import Iterable, Iterator, List, Optional, Sequence, Tuple, Union

import attr
import cirq
from cirq._compat import cached_property
from numpy.typing import NDArray

from cirq_ft import infra
Expand Down
2 changes: 1 addition & 1 deletion cirq-ft/cirq_ft/algos/generic_select.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@

"""Gates for applying generic selected unitaries."""

from functools import cached_property
from typing import Collection, Optional, Sequence, Tuple, Union
from numpy.typing import NDArray

import attr
import cirq
import numpy as np
from cirq._compat import cached_property
from cirq_ft import infra
from cirq_ft.algos import select_and_prepare, unary_iteration_gate

Expand Down
2 changes: 1 addition & 1 deletion cirq-ft/cirq_ft/algos/hubbard_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@
See the documentation for `PrepareHubbard` and `SelectHubbard` for details.
"""
from functools import cached_property
from typing import Collection, Optional, Sequence, Tuple, Union
from numpy.typing import NDArray

import attr
import cirq
import numpy as np
from cirq._compat import cached_property
from cirq_ft import infra
from cirq_ft.algos import and_gate, apply_gate_to_lth_target, arithmetic_gates
from cirq_ft.algos import prepare_uniform_superposition as prep_u
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import cached_property
from typing import Tuple
from numpy.typing import NDArray

import attr
import cirq
from cirq._compat import cached_property
from cirq_ft import infra
from cirq_ft.algos import select_and_prepare
from cirq_ft.algos.mean_estimation import arctan
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import cached_property
import math
from typing import Optional, Tuple

Expand All @@ -20,7 +21,6 @@
import numpy as np
import pytest
from attr import frozen
from cirq._compat import cached_property
from cirq_ft.algos.mean_estimation.complex_phase_oracle import ComplexPhaseOracle
from cirq_ft.infra import bit_tools
from cirq_ft.infra import testing as cq_testing
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import cached_property
from typing import Collection, Optional, Sequence, Tuple, Union
from numpy.typing import NDArray

import attr
import cirq
from cirq._compat import cached_property
from cirq_ft import infra
from cirq_ft.algos import reflection_using_prepare as rup
from cirq_ft.algos import select_and_prepare as sp
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import cached_property
from typing import Optional, Sequence, Tuple

import cirq
Expand All @@ -20,7 +21,6 @@
import pytest
from attr import frozen
from cirq_ft import infra
from cirq._compat import cached_property
from cirq_ft.algos.mean_estimation import CodeForRandomVariable, MeanEstimationOperator
from cirq_ft.infra import bit_tools
from cirq_ft.deprecation import allow_deprecated_cirq_ft_use_in_tests
Expand Down
2 changes: 1 addition & 1 deletion cirq-ft/cirq_ft/algos/multi_control_multi_target_pauli.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import cached_property
from typing import Tuple
from numpy.typing import NDArray

import attr
import cirq
import numpy as np
from cirq._compat import cached_property
from cirq_ft import infra
from cirq_ft.algos import and_gate

Expand Down
2 changes: 1 addition & 1 deletion cirq-ft/cirq_ft/algos/prepare_uniform_superposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from functools import cached_property
from typing import Tuple
from numpy.typing import NDArray

import attr
import cirq
import numpy as np
from cirq._compat import cached_property
from cirq_ft import infra
from cirq_ft.algos import and_gate, arithmetic_gates

Expand Down
3 changes: 2 additions & 1 deletion cirq-ft/cirq_ft/algos/programmable_rotation_gate_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@
# limitations under the License.

import abc
from functools import cached_property
from typing import Sequence, Tuple
from numpy.typing import NDArray

import cirq
import numpy as np
from cirq._compat import cached_method, cached_property
from cirq._compat import cached_method
from cirq_ft import infra
from cirq_ft.algos import qrom
from cirq_ft.infra.bit_tools import iter_bits
Expand Down
Loading

0 comments on commit 968ed4c

Please sign in to comment.