Skip to content

Commit 6dcce44

Browse files
pavoljuhasBichengYing
authored andcommitted
Update sources for mypy-1.11.1 (quantumlib#6707)
- typecheck - purge unused ignore comments - typecheck - address complaints about _ComplexLike expressions - typecheck - fix errors on missing return statement - typecheck - tell mypy it has a callable in inner function - typecheck - fix redundant cast to "str" - typecheck - fix type annotation to kwargs to dataclasses.replace - typecheck - fix signature of the replacement function and restore the original function after the test - typecheck - tell mypy about type when extracted from a zip tuple - typecheck - fix incompatible types in assignment - typecheck - fix type complaint due to unnecessary use of functools.partial - Pick up easy lint from the cirq_google/cloud file - Excise unused stub dependencies in mypy.txt Fixes quantumlib#6705
1 parent 9350704 commit 6dcce44

Some content is hidden

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

43 files changed

+138
-122
lines changed

cirq-core/cirq/circuits/circuit.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2014,7 +2014,7 @@ def transform_qubits(
20142014
if callable(qubit_map):
20152015
transform = qubit_map
20162016
elif isinstance(qubit_map, dict):
2017-
transform = lambda q: qubit_map.get(q, q) # type: ignore
2017+
transform = lambda q: qubit_map.get(q, q)
20182018
else:
20192019
raise TypeError('qubit_map must be a function or dict mapping qubits to qubits.')
20202020

cirq-core/cirq/circuits/circuit_operation.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ def replace(self, **changes) -> 'cirq.CircuitOperation':
267267
'repeat_until': self.repeat_until,
268268
**changes,
269269
}
270-
return CircuitOperation(**kwargs) # type: ignore
270+
return CircuitOperation(**kwargs)
271271

272272
def __eq__(self, other) -> bool:
273273
if not isinstance(other, type(self)):
@@ -688,7 +688,7 @@ def with_qubit_mapping(
688688
if callable(qubit_map):
689689
transform = qubit_map
690690
elif isinstance(qubit_map, dict):
691-
transform = lambda q: qubit_map.get(q, q) # type: ignore
691+
transform = lambda q: qubit_map.get(q, q)
692692
else:
693693
raise TypeError('qubit_map must be a function or dict mapping qubits to qubits.')
694694
new_map = {}

cirq-core/cirq/circuits/qasm_output.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
"""Utility classes for representing QASM."""
1616

17-
from typing import Callable, Dict, Optional, Sequence, Set, Tuple, Union, TYPE_CHECKING
17+
from typing import Callable, Dict, Iterator, Optional, Sequence, Set, Tuple, Union, TYPE_CHECKING
1818

1919
import re
2020
import numpy as np
@@ -126,7 +126,7 @@ def from_matrix(mat: np.ndarray, atol=1e-8) -> 'QasmTwoQubitGate':
126126
def _unitary_(self):
127127
return protocols.unitary(self.kak)
128128

129-
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
129+
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
130130
q0, q1 = qubits
131131
x, y, z = self.kak.interaction_coefficients
132132
a = x * -2 / np.pi + 0.5

cirq-core/cirq/contrib/acquaintance/bipartite.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
import enum
1616
import itertools
17-
from typing import Dict, Sequence, Tuple, Union, TYPE_CHECKING
17+
from typing import Dict, Iterator, Sequence, Tuple, Union, TYPE_CHECKING
1818

1919
from cirq import ops
2020

@@ -72,7 +72,7 @@ def __init__(
7272
)
7373
self.swap_gate = swap_gate
7474

75-
def decompose_complete(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
75+
def decompose_complete(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
7676
swap_gate = SwapPermutationGate(self.swap_gate)
7777
if self.part_size == 1:
7878
yield acquaint(*qubits)
@@ -87,7 +87,7 @@ def decompose_complete(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
8787
yield acquaint(*qubits[x : x + 2])
8888
yield swap_gate(*qubits[x : x + 2])
8989

90-
def decompose_matching(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
90+
def decompose_matching(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
9191
swap_gate = SwapPermutationGate(self.swap_gate)
9292
for k in range(-self.part_size + 1, self.part_size):
9393
for x in range(abs(k), 2 * self.part_size - abs(k), 2):

cirq-core/cirq/contrib/acquaintance/executor.py

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

15-
from typing import DefaultDict, Dict, Sequence, TYPE_CHECKING, Optional
15+
from typing import DefaultDict, Dict, Iterator, Sequence, TYPE_CHECKING, Optional
1616

1717
import abc
1818
from collections import defaultdict
@@ -208,7 +208,7 @@ def device(self) -> 'cirq.Device':
208208

209209
def get_operations(
210210
self, indices: Sequence[LogicalIndex], qubits: Sequence['cirq.Qid']
211-
) -> 'cirq.OP_TREE':
211+
) -> Iterator['cirq.OP_TREE']:
212212
index_set = frozenset(indices)
213213
if index_set in self.index_set_to_gates:
214214
gates = self.index_set_to_gates.pop(index_set)

cirq-core/cirq/contrib/acquaintance/gates.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,17 @@
1616
import itertools
1717
import math
1818
import operator
19-
from typing import Dict, Iterable, List, NamedTuple, Optional, Sequence, Tuple, TYPE_CHECKING
19+
from typing import (
20+
Dict,
21+
Iterable,
22+
Iterator,
23+
List,
24+
NamedTuple,
25+
Optional,
26+
Sequence,
27+
Tuple,
28+
TYPE_CHECKING,
29+
)
2030

2131
from cirq import ops, protocols, value
2232

@@ -276,7 +286,7 @@ def __init__(
276286
self.part_lens = tuple(part_lens)
277287
self.acquaintance_size = acquaintance_size
278288

279-
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
289+
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
280290
qubit_to_position = {q: i for i, q in enumerate(qubits)}
281291
mapping = dict(qubit_to_position)
282292
parts = []

cirq-core/cirq/contrib/acquaintance/inspection_utils.py

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

15-
from typing import FrozenSet, Sequence, Set, TYPE_CHECKING
15+
from typing import FrozenSet, Iterator, Sequence, Set, TYPE_CHECKING
1616

1717
from cirq import devices
1818

@@ -46,7 +46,7 @@ def device(self) -> 'cirq.Device':
4646

4747
def get_operations(
4848
self, indices: Sequence[LogicalIndex], qubits: Sequence['cirq.Qid']
49-
) -> 'cirq.OP_TREE':
49+
) -> Iterator['cirq.OP_TREE']:
5050
yield AcquaintanceOperation(qubits, indices)
5151

5252

cirq-core/cirq/contrib/acquaintance/permutation.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
cast,
1919
Dict,
2020
Iterable,
21+
Iterator,
2122
Optional,
2223
Sequence,
2324
Tuple,
@@ -152,7 +153,7 @@ def __init__(self, swap_gate: 'cirq.Gate' = ops.SWAP):
152153
def permutation(self) -> Dict[int, int]:
153154
return {0: 1, 1: 0}
154155

155-
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
156+
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
156157
yield self.swap_gate(*qubits)
157158

158159
def __repr__(self) -> str:
@@ -201,7 +202,7 @@ def __init__(
201202
def permutation(self) -> Dict[int, int]:
202203
return self._permutation
203204

204-
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
205+
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
205206
swap_gate = SwapPermutationGate(self.swap_gate)
206207
n_qubits = len(qubits)
207208
mapping = {i: self._permutation.get(i, i) for i in range(n_qubits)}

cirq-core/cirq/contrib/acquaintance/shift.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414

1515
import itertools
16-
from typing import Any, Dict, Sequence, Tuple, TYPE_CHECKING
16+
from typing import Any, Dict, Iterator, Sequence, Tuple, TYPE_CHECKING
1717

1818
from cirq import ops, value
1919
from cirq.contrib.acquaintance.permutation import SwapPermutationGate, PermutationGate
@@ -47,7 +47,7 @@ def __repr__(self) -> str:
4747
def _value_equality_values_(self) -> Any:
4848
return self.shift, self.swap_gate, self.num_qubits()
4949

50-
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
50+
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
5151
n = len(qubits)
5252
left_shift = self.shift % n
5353
right_shift = n - left_shift

cirq-core/cirq/contrib/acquaintance/shift_swap_network.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
import functools
1616
import itertools
17-
from typing import Dict, Iterable, Optional, Sequence, Tuple, TYPE_CHECKING
17+
from typing import Dict, Iterable, Iterator, Optional, Sequence, Tuple, TYPE_CHECKING
1818

1919
from cirq import ops
2020
from cirq.contrib.acquaintance.gates import acquaint
@@ -65,7 +65,7 @@ def __init__(
6565
def acquaintance_size(self) -> int:
6666
return sum(max(self.part_lens[side]) for side in ('left', 'right'))
6767

68-
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
68+
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
6969
part_lens = list(itertools.chain(*(self.part_lens[side] for side in ('left', 'right'))))
7070

7171
n_qubits = 0

cirq-core/cirq/contrib/bayesian_network/bayesian_network_gate.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414

1515
import math
16-
from typing import Any, cast, Dict, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union
16+
from typing import Any, cast, Dict, Iterator, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union
1717

1818
from sympy.combinatorics import GrayCode
1919

@@ -158,7 +158,7 @@ def __init__(
158158
raise ValueError('Conditional prob should be between 0 and 1.')
159159
self._arc_probs = arc_probs
160160

161-
def _decompose_(self, qubits: Sequence['raw_types.Qid']) -> 'cirq.OP_TREE':
161+
def _decompose_(self, qubits: Sequence['raw_types.Qid']) -> Iterator['cirq.OP_TREE']:
162162
parameter_names = [init_prob[0] for init_prob in self._init_probs]
163163
qubit_map = dict(zip(parameter_names, qubits))
164164

cirq-core/cirq/contrib/paulistring/separate.py

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

15-
from typing import Tuple
15+
from typing import Iterator, Tuple
1616

1717
from cirq import ops, circuits, transformers
1818

@@ -89,7 +89,7 @@ def pauli_string_half(circuit: circuits.Circuit) -> circuits.Circuit:
8989
)
9090

9191

92-
def _pull_non_clifford_before(circuit: circuits.Circuit) -> ops.OP_TREE:
92+
def _pull_non_clifford_before(circuit: circuits.Circuit) -> Iterator[ops.OP_TREE]:
9393
def _iter_ops_range_reversed(moment_end):
9494
for i in reversed(range(moment_end)):
9595
moment = circuit[i]

cirq-core/cirq/experiments/random_quantum_circuit_generation.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
Container,
2222
Dict,
2323
Iterable,
24+
Iterator,
2425
List,
2526
Sequence,
2627
TYPE_CHECKING,
@@ -691,7 +692,7 @@ def _two_qubit_layer(
691692
],
692693
layer: GridInteractionLayer,
693694
prng: 'np.random.RandomState',
694-
) -> 'cirq.OP_TREE':
695+
) -> Iterator['cirq.OP_TREE']:
695696
for a, b in coupled_qubit_pairs:
696697
if (a, b) in layer or (b, a) in layer:
697698
yield two_qubit_op_factory(a, b, prng)

cirq-core/cirq/interop/quirk/cells/control_cells.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ def modify_column(self, column: List[Optional['Cell']]):
109109
elif gate is not None:
110110
column[i] = gate.controlled_by(self.qubits[0])
111111

112-
def basis_change(self) -> 'cirq.OP_TREE':
112+
def basis_change(self) -> Iterator['cirq.OP_TREE']:
113113
yield from self._basis_change
114114

115115
# Temporarily move the ZZZ..Z parity observable onto a single qubit.

cirq-core/cirq/interop/quirk/cells/parse.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,9 @@ def feed_op(could_be_binary: bool, token: Any) -> None:
191191
elif token.unary_action is not None:
192192
burn_ops(token.priority)
193193
vals.append(None)
194-
ops.append(_HangingNode(func=lambda _, b: token.unary_action(b), weight=np.inf))
194+
# this avoids mypy complaint about None not being callable
195+
token_unary_action = token.unary_action
196+
ops.append(_HangingNode(func=lambda _, b: token_unary_action(b), weight=np.inf))
195197
elif token.binary_action is not None:
196198
raise ValueError("Bad expression: binary op in bad spot.\ntext={text!r}")
197199

cirq-core/cirq/ops/diagonal_gate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def _decompose_for_basis(
166166
self, index: int, bit_flip: int, theta: 'cirq.TParamVal', qubits: Sequence['cirq.Qid']
167167
) -> Iterator[Union['cirq.ZPowGate', 'cirq.CXPowGate']]:
168168
if index == 0:
169-
return []
169+
return
170170
largest_digit = self._num_qubits_() - (len(bin(index)) - 2)
171171
yield common_gates.rz(2 * theta)(qubits[largest_digit])
172172
_flip_bit = self._num_qubits_() - bit_flip - 1

cirq-core/cirq/ops/fsim_gate.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
import cmath
2525
import math
26-
from typing import AbstractSet, Any, Dict, Optional, Tuple
26+
from typing import AbstractSet, Any, Dict, Iterator, Optional, Tuple
2727

2828
import numpy as np
2929
import sympy
@@ -187,7 +187,7 @@ def _apply_unitary_(self, args: 'cirq.ApplyUnitaryArgs') -> Optional[np.ndarray]
187187
out[ii] *= cmath.exp(-1j * self.phi)
188188
return out
189189

190-
def _decompose_(self, qubits) -> 'cirq.OP_TREE':
190+
def _decompose_(self, qubits) -> Iterator['cirq.OP_TREE']:
191191
a, b = qubits
192192
xx = cirq.XXPowGate(exponent=self.theta / np.pi, global_shift=-0.5)
193193
yy = cirq.YYPowGate(exponent=self.theta / np.pi, global_shift=-0.5)
@@ -452,7 +452,7 @@ def _apply_unitary_(self, args: 'cirq.ApplyUnitaryArgs') -> Optional[np.ndarray]
452452
out[ii] *= f * f
453453
return out
454454

455-
def _decompose_(self, qubits) -> 'cirq.OP_TREE':
455+
def _decompose_(self, qubits) -> Iterator['cirq.OP_TREE']:
456456
"""Decomposes self into Z rotations and FSimGate.
457457
458458
Note that Z rotations returned by this method have unusual global phase

cirq-core/cirq/ops/linear_combinations.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -805,7 +805,7 @@ def __imul__(self, other: PauliSumLike):
805805
if not isinstance(other, (numbers.Complex, PauliString, PauliSum)):
806806
return NotImplemented
807807
if isinstance(other, numbers.Complex):
808-
self._linear_dict *= other
808+
self._linear_dict *= complex(other)
809809
elif isinstance(other, PauliString):
810810
temp = PauliSum.from_pauli_strings([term * other for term in self])
811811
self._linear_dict = temp._linear_dict

cirq-core/cirq/ops/parity_gates.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
"""Quantum gates that phase with respect to product-of-pauli observables."""
1616

17-
from typing import Any, Dict, List, Optional, Tuple, Union, TYPE_CHECKING, Sequence
17+
from typing import Any, Dict, List, Iterator, Optional, Tuple, Union, TYPE_CHECKING, Sequence
1818
from typing_extensions import Self
1919

2020
import numpy as np
@@ -118,7 +118,7 @@ def _decompose_into_clifford_with_qubits_(self, qubits):
118118
def _has_stabilizer_effect_(self) -> bool:
119119
return self.exponent % 2 in (0, 0.5, 1, 1.5)
120120

121-
def _decompose_(self, qubits: Tuple['cirq.Qid', ...]) -> 'cirq.OP_TREE':
121+
def _decompose_(self, qubits: Tuple['cirq.Qid', ...]) -> Iterator['cirq.OP_TREE']:
122122
yield common_gates.YPowGate(exponent=-0.5).on_each(*qubits)
123123
yield ZZPowGate(exponent=self.exponent, global_shift=self.global_shift)(*qubits)
124124
yield common_gates.YPowGate(exponent=0.5).on_each(*qubits)
@@ -227,7 +227,7 @@ def _decompose_into_clifford_with_qubits_(self, qubits):
227227
def _has_stabilizer_effect_(self) -> bool:
228228
return self.exponent % 2 in (0, 0.5, 1, 1.5)
229229

230-
def _decompose_(self, qubits: Tuple['cirq.Qid', ...]) -> 'cirq.OP_TREE':
230+
def _decompose_(self, qubits: Tuple['cirq.Qid', ...]) -> Iterator['cirq.OP_TREE']:
231231
yield common_gates.XPowGate(exponent=0.5).on_each(*qubits)
232232
yield ZZPowGate(exponent=self.exponent, global_shift=self.global_shift)(*qubits)
233233
yield common_gates.XPowGate(exponent=-0.5).on_each(*qubits)

cirq-core/cirq/ops/pauli_interaction_gate.py

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

15-
from typing import Any, Dict, List, Sequence, TYPE_CHECKING, Tuple
15+
from typing import Any, Dict, Iterator, List, Sequence, TYPE_CHECKING, Tuple
1616

1717
import numpy as np
1818

@@ -108,7 +108,7 @@ def _eigen_components(self) -> List[Tuple[float, np.ndarray]]:
108108
comp0 = np.eye(4) - comp1
109109
return [(0, comp0), (1, comp1)]
110110

111-
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
111+
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
112112
q0, q1 = qubits
113113
right_gate0 = SingleQubitCliffordGate.from_single_map(z_to=(self.pauli0, self.invert0))
114114
right_gate1 = SingleQubitCliffordGate.from_single_map(z_to=(self.pauli1, self.invert1))

cirq-core/cirq/ops/pauli_measurement_gate.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
Dict,
1818
FrozenSet,
1919
Iterable,
20+
Iterator,
2021
Mapping,
2122
Tuple,
2223
Sequence,
@@ -144,7 +145,7 @@ def observable(self) -> 'cirq.DensePauliString':
144145

145146
def _decompose_(
146147
self, qubits: Tuple['cirq.Qid', ...]
147-
) -> 'protocols.decompose_protocol.DecomposeResult':
148+
) -> Iterator['protocols.decompose_protocol.DecomposeResult']:
148149
any_qubit = qubits[0]
149150
to_z_ops = op_tree.freeze_op_tree(self._observable.on(*qubits).to_z_basis_ops())
150151
xor_decomp = tuple(pauli_string_phasor.xor_nonlocal_decompose(qubits, any_qubit))

cirq-core/cirq/ops/pauli_string_phasor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,7 @@ def _to_z_basis_ops(self, qubits: Sequence['cirq.Qid']) -> Iterator[raw_types.Op
351351
"""Returns operations to convert the qubits to the computational basis."""
352352
return self.dense_pauli_string.on(*qubits).to_z_basis_ops()
353353

354-
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
354+
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
355355
if len(self.dense_pauli_string) <= 0:
356356
return
357357
any_qubit = qubits[0]

0 commit comments

Comments
 (0)