Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
e4a8e30
Update to mypy-1.11.1
pavoljuhas Aug 21, 2024
12cb396
typecheck - purge unused ignore comments
pavoljuhas Aug 19, 2024
fb1e238
typecheck - address complaints about _ComplexLike expressions
pavoljuhas Aug 20, 2024
b0480b8
typecheck - fix errors on missing return statement
pavoljuhas Aug 20, 2024
64e6708
typecheck - tell mypy it has a callable in inner function
pavoljuhas Aug 20, 2024
d7ae150
typecheck - fix redundant cast to "str"
pavoljuhas Aug 21, 2024
e49d616
typecheck - fix type annotation to kwargs to dataclasses.replace
pavoljuhas Aug 21, 2024
d316684
typecheck - fix signature of the replacement function
pavoljuhas Aug 21, 2024
eb9ba15
typecheck - tell mypy about type when extracted from a zip tuple
pavoljuhas Aug 21, 2024
88e0426
typecheck - fix incompatible types in assignment
pavoljuhas Aug 21, 2024
4ff105b
typecheck - fix type complaint due to unnecessary use of functools.pa…
pavoljuhas Aug 21, 2024
6c41e25
Pick up easy lint from the cirq_google/cloud file
pavoljuhas Aug 21, 2024
63f558f
Excise unused stub dependencies
pavoljuhas Aug 21, 2024
787a6c2
Put back type stubs for setuptools
pavoljuhas Aug 21, 2024
00765f0
typecheck - support numpy scalar types in LinearDict
pavoljuhas Aug 23, 2024
c4966f9
Future bright future will you satisfy mypy?
pavoljuhas Aug 23, 2024
b32f04e
Use `math.prod` for painless typecheck
pavoljuhas Aug 23, 2024
f7da161
Ensure test does not change API function
pavoljuhas Aug 23, 2024
b8893ca
Combine imports in cirq-ionq/cirq_ionq/ionq_gateset.py
pavoljuhas Aug 23, 2024
963b558
Merge branch 'main' into sync-with-mypy-1.11.1
pavoljuhas Aug 23, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cirq-core/cirq/circuits/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -2014,7 +2014,7 @@ def transform_qubits(
if callable(qubit_map):
transform = qubit_map
elif isinstance(qubit_map, dict):
transform = lambda q: qubit_map.get(q, q) # type: ignore
transform = lambda q: qubit_map.get(q, q)
else:
raise TypeError('qubit_map must be a function or dict mapping qubits to qubits.')

Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/circuits/circuit_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ def replace(self, **changes) -> 'cirq.CircuitOperation':
'repeat_until': self.repeat_until,
**changes,
}
return CircuitOperation(**kwargs) # type: ignore
return CircuitOperation(**kwargs)

def __eq__(self, other) -> bool:
if not isinstance(other, type(self)):
Expand Down Expand Up @@ -688,7 +688,7 @@ def with_qubit_mapping(
if callable(qubit_map):
transform = qubit_map
elif isinstance(qubit_map, dict):
transform = lambda q: qubit_map.get(q, q) # type: ignore
transform = lambda q: qubit_map.get(q, q)
else:
raise TypeError('qubit_map must be a function or dict mapping qubits to qubits.')
new_map = {}
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/circuits/qasm_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

"""Utility classes for representing QASM."""

from typing import Callable, Dict, Optional, Sequence, Set, Tuple, Union, TYPE_CHECKING
from typing import Callable, Dict, Iterator, Optional, Sequence, Set, Tuple, Union, TYPE_CHECKING

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

def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
q0, q1 = qubits
x, y, z = self.kak.interaction_coefficients
a = x * -2 / np.pi + 0.5
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/contrib/acquaintance/bipartite.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import enum
import itertools
from typing import Dict, Sequence, Tuple, Union, TYPE_CHECKING
from typing import Dict, Iterator, Sequence, Tuple, Union, TYPE_CHECKING

from cirq import ops

Expand Down Expand Up @@ -72,7 +72,7 @@ def __init__(
)
self.swap_gate = swap_gate

def decompose_complete(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
def decompose_complete(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
swap_gate = SwapPermutationGate(self.swap_gate)
if self.part_size == 1:
yield acquaint(*qubits)
Expand All @@ -87,7 +87,7 @@ def decompose_complete(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
yield acquaint(*qubits[x : x + 2])
yield swap_gate(*qubits[x : x + 2])

def decompose_matching(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
def decompose_matching(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
swap_gate = SwapPermutationGate(self.swap_gate)
for k in range(-self.part_size + 1, self.part_size):
for x in range(abs(k), 2 * self.part_size - abs(k), 2):
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/contrib/acquaintance/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import DefaultDict, Dict, Sequence, TYPE_CHECKING, Optional
from typing import DefaultDict, Dict, Iterator, Sequence, TYPE_CHECKING, Optional

import abc
from collections import defaultdict
Expand Down Expand Up @@ -208,7 +208,7 @@ def device(self) -> 'cirq.Device':

def get_operations(
self, indices: Sequence[LogicalIndex], qubits: Sequence['cirq.Qid']
) -> 'cirq.OP_TREE':
) -> Iterator['cirq.OP_TREE']:
index_set = frozenset(indices)
if index_set in self.index_set_to_gates:
gates = self.index_set_to_gates.pop(index_set)
Expand Down
14 changes: 12 additions & 2 deletions cirq-core/cirq/contrib/acquaintance/gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,17 @@
import itertools
import math
import operator
from typing import Dict, Iterable, List, NamedTuple, Optional, Sequence, Tuple, TYPE_CHECKING
from typing import (
Dict,
Iterable,
Iterator,
List,
NamedTuple,
Optional,
Sequence,
Tuple,
TYPE_CHECKING,
)

from cirq import ops, protocols, value

Expand Down Expand Up @@ -276,7 +286,7 @@ def __init__(
self.part_lens = tuple(part_lens)
self.acquaintance_size = acquaintance_size

def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
qubit_to_position = {q: i for i, q in enumerate(qubits)}
mapping = dict(qubit_to_position)
parts = []
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/contrib/acquaintance/inspection_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import FrozenSet, Sequence, Set, TYPE_CHECKING
from typing import FrozenSet, Iterator, Sequence, Set, TYPE_CHECKING

from cirq import devices

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

def get_operations(
self, indices: Sequence[LogicalIndex], qubits: Sequence['cirq.Qid']
) -> 'cirq.OP_TREE':
) -> Iterator['cirq.OP_TREE']:
yield AcquaintanceOperation(qubits, indices)


Expand Down
5 changes: 3 additions & 2 deletions cirq-core/cirq/contrib/acquaintance/permutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
cast,
Dict,
Iterable,
Iterator,
Optional,
Sequence,
Tuple,
Expand Down Expand Up @@ -152,7 +153,7 @@ def __init__(self, swap_gate: 'cirq.Gate' = ops.SWAP):
def permutation(self) -> Dict[int, int]:
return {0: 1, 1: 0}

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

def __repr__(self) -> str:
Expand Down Expand Up @@ -201,7 +202,7 @@ def __init__(
def permutation(self) -> Dict[int, int]:
return self._permutation

def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
swap_gate = SwapPermutationGate(self.swap_gate)
n_qubits = len(qubits)
mapping = {i: self._permutation.get(i, i) for i in range(n_qubits)}
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/contrib/acquaintance/shift.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

import itertools
from typing import Any, Dict, Sequence, Tuple, TYPE_CHECKING
from typing import Any, Dict, Iterator, Sequence, Tuple, TYPE_CHECKING

from cirq import ops, value
from cirq.contrib.acquaintance.permutation import SwapPermutationGate, PermutationGate
Expand Down Expand Up @@ -47,7 +47,7 @@ def __repr__(self) -> str:
def _value_equality_values_(self) -> Any:
return self.shift, self.swap_gate, self.num_qubits()

def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
n = len(qubits)
left_shift = self.shift % n
right_shift = n - left_shift
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/contrib/acquaintance/shift_swap_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import functools
import itertools
from typing import Dict, Iterable, Optional, Sequence, Tuple, TYPE_CHECKING
from typing import Dict, Iterable, Iterator, Optional, Sequence, Tuple, TYPE_CHECKING

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

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

n_qubits = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

import math
from typing import Any, cast, Dict, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union
from typing import Any, cast, Dict, Iterator, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union

from sympy.combinatorics import GrayCode

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

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

Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/contrib/paulistring/separate.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Tuple
from typing import Iterator, Tuple

from cirq import ops, circuits, transformers

Expand Down Expand Up @@ -89,7 +89,7 @@ def pauli_string_half(circuit: circuits.Circuit) -> circuits.Circuit:
)


def _pull_non_clifford_before(circuit: circuits.Circuit) -> ops.OP_TREE:
def _pull_non_clifford_before(circuit: circuits.Circuit) -> Iterator[ops.OP_TREE]:
def _iter_ops_range_reversed(moment_end):
for i in reversed(range(moment_end)):
moment = circuit[i]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
Container,
Dict,
Iterable,
Iterator,
List,
Sequence,
TYPE_CHECKING,
Expand Down Expand Up @@ -691,7 +692,7 @@ def _two_qubit_layer(
],
layer: GridInteractionLayer,
prng: 'np.random.RandomState',
) -> 'cirq.OP_TREE':
) -> Iterator['cirq.OP_TREE']:
for a, b in coupled_qubit_pairs:
if (a, b) in layer or (b, a) in layer:
yield two_qubit_op_factory(a, b, prng)
2 changes: 1 addition & 1 deletion cirq-core/cirq/interop/quirk/cells/control_cells.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def modify_column(self, column: List[Optional['Cell']]):
elif gate is not None:
column[i] = gate.controlled_by(self.qubits[0])

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

# Temporarily move the ZZZ..Z parity observable onto a single qubit.
Expand Down
4 changes: 3 additions & 1 deletion cirq-core/cirq/interop/quirk/cells/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,9 @@ def feed_op(could_be_binary: bool, token: Any) -> None:
elif token.unary_action is not None:
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consider using a walrus operator here:

Suggested change
elif token.unary_action is not None:
elif (action := token.unary_action) is not None:

Then lambda _, b: action(b) should work.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ack. I feel the current version makes it a bit more clear why is the attribute stored in a local var.

burn_ops(token.priority)
vals.append(None)
ops.append(_HangingNode(func=lambda _, b: token.unary_action(b), weight=np.inf))
# this avoids mypy complaint about None not being callable
token_unary_action = token.unary_action
ops.append(_HangingNode(func=lambda _, b: token_unary_action(b), weight=np.inf))
elif token.binary_action is not None:
raise ValueError("Bad expression: binary op in bad spot.\ntext={text!r}")

Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/diagonal_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def _decompose_for_basis(
self, index: int, bit_flip: int, theta: 'cirq.TParamVal', qubits: Sequence['cirq.Qid']
) -> Iterator[Union['cirq.ZPowGate', 'cirq.CXPowGate']]:
if index == 0:
return []
return
largest_digit = self._num_qubits_() - (len(bin(index)) - 2)
yield common_gates.rz(2 * theta)(qubits[largest_digit])
_flip_bit = self._num_qubits_() - bit_flip - 1
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/ops/fsim_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

import cmath
import math
from typing import AbstractSet, Any, Dict, Optional, Tuple
from typing import AbstractSet, Any, Dict, Iterator, Optional, Tuple

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

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

def _decompose_(self, qubits) -> 'cirq.OP_TREE':
def _decompose_(self, qubits) -> Iterator['cirq.OP_TREE']:
"""Decomposes self into Z rotations and FSimGate.

Note that Z rotations returned by this method have unusual global phase
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/linear_combinations.py
Original file line number Diff line number Diff line change
Expand Up @@ -805,7 +805,7 @@ def __imul__(self, other: PauliSumLike):
if not isinstance(other, (numbers.Complex, PauliString, PauliSum)):
return NotImplemented
if isinstance(other, numbers.Complex):
self._linear_dict *= other
self._linear_dict *= complex(other)
elif isinstance(other, PauliString):
temp = PauliSum.from_pauli_strings([term * other for term in self])
self._linear_dict = temp._linear_dict
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/ops/parity_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

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

from typing import Any, Dict, List, Optional, Tuple, Union, TYPE_CHECKING, Sequence
from typing import Any, Dict, List, Iterator, Optional, Tuple, Union, TYPE_CHECKING, Sequence
from typing_extensions import Self

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

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

def _decompose_(self, qubits: Tuple['cirq.Qid', ...]) -> 'cirq.OP_TREE':
def _decompose_(self, qubits: Tuple['cirq.Qid', ...]) -> Iterator['cirq.OP_TREE']:
yield common_gates.XPowGate(exponent=0.5).on_each(*qubits)
yield ZZPowGate(exponent=self.exponent, global_shift=self.global_shift)(*qubits)
yield common_gates.XPowGate(exponent=-0.5).on_each(*qubits)
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/ops/pauli_interaction_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import Any, Dict, List, Sequence, TYPE_CHECKING, Tuple
from typing import Any, Dict, Iterator, List, Sequence, TYPE_CHECKING, Tuple

import numpy as np

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

def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
q0, q1 = qubits
right_gate0 = SingleQubitCliffordGate.from_single_map(z_to=(self.pauli0, self.invert0))
right_gate1 = SingleQubitCliffordGate.from_single_map(z_to=(self.pauli1, self.invert1))
Expand Down
3 changes: 2 additions & 1 deletion cirq-core/cirq/ops/pauli_measurement_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
Dict,
FrozenSet,
Iterable,
Iterator,
Mapping,
Tuple,
Sequence,
Expand Down Expand Up @@ -144,7 +145,7 @@ def observable(self) -> 'cirq.DensePauliString':

def _decompose_(
self, qubits: Tuple['cirq.Qid', ...]
) -> 'protocols.decompose_protocol.DecomposeResult':
) -> Iterator['protocols.decompose_protocol.DecomposeResult']:
any_qubit = qubits[0]
to_z_ops = op_tree.freeze_op_tree(self._observable.on(*qubits).to_z_basis_ops())
xor_decomp = tuple(pauli_string_phasor.xor_nonlocal_decompose(qubits, any_qubit))
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/pauli_string_phasor.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ def _to_z_basis_ops(self, qubits: Sequence['cirq.Qid']) -> Iterator[raw_types.Op
"""Returns operations to convert the qubits to the computational basis."""
return self.dense_pauli_string.on(*qubits).to_z_basis_ops()

def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
def _decompose_(self, qubits: Sequence['cirq.Qid']) -> Iterator['cirq.OP_TREE']:
if len(self.dense_pauli_string) <= 0:
return
any_qubit = qubits[0]
Expand Down
Loading