Skip to content

Commit 4fa82fb

Browse files
authored
Switch to unquoted type annotations part 4 (#7298)
No change in the effective code. A batch of 50 files (49 changed, 1 good). Passes ruff check --target-version=py310 --select=UP037,TC001 Partially implements #1999
1 parent 5f7fc9a commit 4fa82fb

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+576
-495
lines changed

cirq-core/cirq/protocols/measurement_key_protocol.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,11 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
1415
"""Protocol for object that have measurement keys."""
1516

17+
from __future__ import annotations
18+
1619
from types import NotImplementedType
1720
from typing import Any, FrozenSet, Mapping, Optional, Tuple, TYPE_CHECKING, Union
1821

@@ -60,7 +63,7 @@ def _is_measurement_(self) -> bool:
6063
"""Return if this object is (or contains) a measurement."""
6164

6265
@doc_private
63-
def _measurement_key_obj_(self) -> 'cirq.MeasurementKey':
66+
def _measurement_key_obj_(self) -> cirq.MeasurementKey:
6467
"""Return the key object that will be used to identify this measurement.
6568
6669
When a measurement occurs, either on hardware, or in a simulation,
@@ -71,7 +74,7 @@ def _measurement_key_obj_(self) -> 'cirq.MeasurementKey':
7174
@doc_private
7275
def _measurement_key_objs_(
7376
self,
74-
) -> Union[FrozenSet['cirq.MeasurementKey'], NotImplementedType, None]:
77+
) -> Union[FrozenSet[cirq.MeasurementKey], NotImplementedType, None]:
7578
"""Return the key objects for measurements performed by the receiving object.
7679
7780
When a measurement occurs, either on hardware, or in a simulation,
@@ -175,7 +178,7 @@ def measurement_key_name(val: Any, default: Any = RaiseTypeErrorIfNotProvided):
175178

176179
def _measurement_key_objs_from_magic_methods(
177180
val: Any,
178-
) -> Union[FrozenSet['cirq.MeasurementKey'], NotImplementedType, None]:
181+
) -> Union[FrozenSet[cirq.MeasurementKey], NotImplementedType, None]:
179182
"""Uses the measurement key related magic methods to get the `MeasurementKey`s for this
180183
object."""
181184

@@ -209,7 +212,7 @@ def _measurement_key_names_from_magic_methods(
209212
return result
210213

211214

212-
def measurement_key_objs(val: Any) -> FrozenSet['cirq.MeasurementKey']:
215+
def measurement_key_objs(val: Any) -> FrozenSet[cirq.MeasurementKey]:
213216
"""Gets the measurement key objects of measurements within the given value.
214217
215218
Args:
@@ -316,9 +319,7 @@ def with_key_path_prefix(val: Any, prefix: Tuple[str, ...]):
316319

317320

318321
def with_rescoped_keys(
319-
val: Any,
320-
path: Tuple[str, ...],
321-
bindable_keys: Optional[FrozenSet['cirq.MeasurementKey']] = None,
322+
val: Any, path: Tuple[str, ...], bindable_keys: Optional[FrozenSet[cirq.MeasurementKey]] = None
322323
):
323324
"""Rescopes any measurement and control keys to the provided path, given the existing keys.
324325

cirq-core/cirq/protocols/pow_protocol.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from __future__ import annotations
16+
1517
from typing import Any, Callable, Optional, overload, TYPE_CHECKING, TypeVar, Union
1618

1719
if TYPE_CHECKING:
@@ -26,29 +28,27 @@
2628

2729
# pylint: disable=function-redefined, redefined-builtin
2830
@overload
29-
def pow(val: 'cirq.Gate', exponent: Any) -> 'cirq.Gate':
31+
def pow(val: cirq.Gate, exponent: Any) -> cirq.Gate:
3032
pass
3133

3234

3335
@overload
34-
def pow(val: 'cirq.Operation', exponent: Any) -> 'cirq.Operation':
36+
def pow(val: cirq.Operation, exponent: Any) -> cirq.Operation:
3537
pass
3638

3739

3840
@overload
39-
def pow(val: 'cirq.Gate', exponent: Any, default: TDefault) -> Union[TDefault, 'cirq.Gate']:
41+
def pow(val: cirq.Gate, exponent: Any, default: TDefault) -> Union[TDefault, cirq.Gate]:
4042
pass
4143

4244

4345
@overload
44-
def pow(
45-
val: 'cirq.Operation', exponent: Any, default: TDefault
46-
) -> Union[TDefault, 'cirq.Operation']:
46+
def pow(val: cirq.Operation, exponent: Any, default: TDefault) -> Union[TDefault, cirq.Operation]:
4747
pass
4848

4949

5050
@overload
51-
def pow(val: 'cirq.Circuit', exponent: int, default: TDefault) -> Union[TDefault, 'cirq.Circuit']:
51+
def pow(val: cirq.Circuit, exponent: int, default: TDefault) -> Union[TDefault, cirq.Circuit]:
5252
pass
5353

5454

cirq-core/cirq/protocols/qasm.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from __future__ import annotations
16+
1517
import string
1618
from types import NotImplementedType
1719
from typing import Any, Dict, Iterable, Optional, Tuple, TYPE_CHECKING, TypeVar, Union
@@ -36,7 +38,7 @@ def __init__(
3638
self,
3739
precision: int = 10,
3840
version: str = '2.0',
39-
qubit_id_map: Optional[Dict['cirq.Qid', str]] = None,
41+
qubit_id_map: Optional[Dict[cirq.Qid, str]] = None,
4042
meas_key_id_map: Optional[Dict[str, str]] = None,
4143
meas_key_bitcount: Optional[Dict[str, int]] = None,
4244
) -> None:
@@ -124,7 +126,7 @@ class SupportsQasmWithArgsAndQubits(Protocol):
124126

125127
@doc_private
126128
def _qasm_(
127-
self, qubits: Tuple['cirq.Qid'], args: QasmArgs
129+
self, qubits: Tuple[cirq.Qid], args: QasmArgs
128130
) -> Union[None, NotImplementedType, str]:
129131
pass
130132

@@ -134,7 +136,7 @@ def qasm(
134136
val: Any,
135137
*,
136138
args: Optional[QasmArgs] = None,
137-
qubits: Optional[Iterable['cirq.Qid']] = None,
139+
qubits: Optional[Iterable[cirq.Qid]] = None,
138140
default: TDefault = RaiseTypeErrorIfNotProvided,
139141
) -> Union[str, TDefault]:
140142
"""Returns QASM code for the given value, if possible.

cirq-core/cirq/protocols/resolve_parameters.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from __future__ import annotations
16+
1517
import numbers
1618
from typing import AbstractSet, Any, cast, TYPE_CHECKING, TypeVar
1719

@@ -48,7 +50,7 @@ def _parameter_names_(self) -> AbstractSet[str]:
4850
"""
4951

5052
@doc_private
51-
def _resolve_parameters_(self, resolver: 'cirq.ParamResolver', recursive: bool) -> Self:
53+
def _resolve_parameters_(self, resolver: cirq.ParamResolver, recursive: bool) -> Self:
5254
"""Resolve the parameters in the effect."""
5355

5456

@@ -133,7 +135,7 @@ def parameter_symbols(val: Any) -> AbstractSet[sympy.Symbol]:
133135

134136

135137
def resolve_parameters(
136-
val: T, param_resolver: 'cirq.ParamResolverOrSimilarType', recursive: bool = True
138+
val: T, param_resolver: cirq.ParamResolverOrSimilarType, recursive: bool = True
137139
) -> T:
138140
"""Resolves symbol parameters in the effect using the param resolver.
139141
@@ -195,6 +197,6 @@ def resolve_parameters(
195197
return val
196198

197199

198-
def resolve_parameters_once(val: Any, param_resolver: 'cirq.ParamResolverOrSimilarType'):
200+
def resolve_parameters_once(val: Any, param_resolver: cirq.ParamResolverOrSimilarType):
199201
"""Performs a single parameter resolution step using the param resolver."""
200202
return resolve_parameters(val, param_resolver, False)

cirq-core/cirq/qis/clifford_tableau.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from __future__ import annotations
16+
1517
import abc
1618
from typing import Any, Dict, List, Optional, Sequence, TYPE_CHECKING
1719

@@ -286,10 +288,10 @@ def __eq__(self, other):
286288
and np.array_equal(self.zs, other.zs)
287289
)
288290

289-
def __copy__(self) -> 'CliffordTableau':
291+
def __copy__(self) -> CliffordTableau:
290292
return self.copy()
291293

292-
def copy(self, deep_copy_buffers: bool = True) -> 'CliffordTableau':
294+
def copy(self, deep_copy_buffers: bool = True) -> CliffordTableau:
293295
state = CliffordTableau(self.n)
294296
state.rs = self.rs.copy()
295297
state.xs = self.xs.copy()
@@ -364,7 +366,7 @@ def _pauli_from_matrix(r: int, c: int) -> str:
364366

365367
return '\n'.join([title_row, divider, *contents]) + '\n'
366368

367-
def then(self, second: 'CliffordTableau') -> 'CliffordTableau':
369+
def then(self, second: CliffordTableau) -> CliffordTableau:
368370
"""Returns a composed CliffordTableau of this tableau and the second tableau.
369371
370372
Then composed tableau is equal to (up to global phase) the composed
@@ -431,7 +433,7 @@ def then(self, second: 'CliffordTableau') -> 'CliffordTableau':
431433

432434
return merged_tableau
433435

434-
def inverse(self) -> 'CliffordTableau':
436+
def inverse(self) -> CliffordTableau:
435437
"""Returns the inverse Clifford tableau of this tableau."""
436438
ret_table = CliffordTableau(num_qubits=self.n)
437439
# It relies on the symplectic property of Clifford tableau.
@@ -450,7 +452,7 @@ def inverse(self) -> 'CliffordTableau':
450452
ret_table.rs = ret_table.then(self).rs
451453
return ret_table
452454

453-
def __matmul__(self, second: 'CliffordTableau'):
455+
def __matmul__(self, second: CliffordTableau):
454456
if not isinstance(second, CliffordTableau):
455457
return NotImplemented
456458
return second.then(self)
@@ -481,7 +483,7 @@ def g(x1, z1, x2, z2):
481483
self._xs[q1, :] ^= self._xs[q2, :]
482484
self._zs[q1, :] ^= self._zs[q2, :]
483485

484-
def _row_to_dense_pauli(self, i: int) -> 'cirq.DensePauliString':
486+
def _row_to_dense_pauli(self, i: int) -> cirq.DensePauliString:
485487
"""Return a dense Pauli string for the given row in the tableau.
486488
487489
Args:
@@ -509,12 +511,12 @@ def _row_to_dense_pauli(self, i: int) -> 'cirq.DensePauliString':
509511
pauli_mask += "I"
510512
return DensePauliString(pauli_mask, coefficient=coefficient)
511513

512-
def stabilizers(self) -> List['cirq.DensePauliString']:
514+
def stabilizers(self) -> List[cirq.DensePauliString]:
513515
"""Returns the stabilizer generators of the state. These
514516
are n operators {S_1,S_2,...,S_n} such that S_i |psi> = |psi>"""
515517
return [self._row_to_dense_pauli(i) for i in range(self.n, 2 * self.n)]
516518

517-
def destabilizers(self) -> List['cirq.DensePauliString']:
519+
def destabilizers(self) -> List[cirq.DensePauliString]:
518520
"""Returns the destabilizer generators of the state. These
519521
are n operators {S_1,S_2,...,S_n} such that along with the stabilizer
520522
generators above generate the full Pauli group on n qubits."""
@@ -662,7 +664,7 @@ def apply_global_phase(self, coefficient: linear_dict.Scalar):
662664
pass
663665

664666
def measure(
665-
self, axes: Sequence[int], seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None
667+
self, axes: Sequence[int], seed: cirq.RANDOM_STATE_OR_SEED_LIKE = None
666668
) -> List[int]:
667669
return [self._measure(axis, random_state.parse_random_state(seed)) for axis in axes]
668670

cirq-core/cirq/qis/measures.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,10 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
1415
"""Measures on and between quantum states and operations."""
1516

17+
from __future__ import annotations
1618

1719
from typing import Optional, Tuple, TYPE_CHECKING
1820

@@ -58,9 +60,7 @@ def _validate_int_state(state: int, qid_shape: Optional[Tuple[int, ...]]) -> Non
5860
)
5961

6062

61-
def _validate_product_state(
62-
state: 'cirq.ProductState', qid_shape: Optional[Tuple[int, ...]]
63-
) -> None:
63+
def _validate_product_state(state: cirq.ProductState, qid_shape: Optional[Tuple[int, ...]]) -> None:
6464
if qid_shape is not None and qid_shape != (2,) * len(state):
6565
raise ValueError(
6666
'Invalid state for given qid shape: '
@@ -70,8 +70,8 @@ def _validate_product_state(
7070

7171

7272
def fidelity(
73-
state1: 'cirq.QUANTUM_STATE_LIKE',
74-
state2: 'cirq.QUANTUM_STATE_LIKE',
73+
state1: cirq.QUANTUM_STATE_LIKE,
74+
state2: cirq.QUANTUM_STATE_LIKE,
7575
qid_shape: Optional[Tuple[int, ...]] = None,
7676
validate: bool = True,
7777
atol: float = 1e-7,
@@ -255,7 +255,7 @@ def _fidelity_state_vectors_or_density_matrices(state1: np.ndarray, state2: np.n
255255

256256

257257
def von_neumann_entropy(
258-
state: 'cirq.QUANTUM_STATE_LIKE',
258+
state: cirq.QUANTUM_STATE_LIKE,
259259
qid_shape: Optional[Tuple[int, ...]] = None,
260260
validate: bool = True,
261261
atol: float = 1e-7,
@@ -298,7 +298,7 @@ def von_neumann_entropy(
298298
return 0.0
299299

300300

301-
def entanglement_fidelity(operation: 'cirq.SupportsKraus') -> float:
301+
def entanglement_fidelity(operation: cirq.SupportsKraus) -> float:
302302
r"""Returns entanglement fidelity of a given quantum channel.
303303
304304
Entanglement fidelity $F_e$ of a quantum channel $E: L(H) \to L(H)$ is the overlap between

cirq-core/cirq/qis/quantum_state_representation.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from __future__ import annotations
16+
1517
import abc
1618
from typing import List, Sequence, Tuple, TYPE_CHECKING
1719

@@ -38,7 +40,7 @@ def copy(self, deep_copy_buffers: bool = True) -> Self:
3840

3941
@abc.abstractmethod
4042
def measure(
41-
self, axes: Sequence[int], seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None
43+
self, axes: Sequence[int], seed: cirq.RANDOM_STATE_OR_SEED_LIKE = None
4244
) -> List[int]:
4345
"""Measures the state.
4446
@@ -50,10 +52,7 @@ def measure(
5052
"""
5153

5254
def sample(
53-
self,
54-
axes: Sequence[int],
55-
repetitions: int = 1,
56-
seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,
55+
self, axes: Sequence[int], repetitions: int = 1, seed: cirq.RANDOM_STATE_OR_SEED_LIKE = None
5756
) -> np.ndarray:
5857
"""Samples the state. Subclasses can override with more performant method.
5958

0 commit comments

Comments
 (0)