Skip to content

Commit

Permalink
Remove unnecessary casts and type: ignores (quantumlib#5781)
Browse files Browse the repository at this point in the history
Update mypy configuration to fail if there are unnecessary `cast` calls or `type: ignore` comments, so that we clean these up rather than accumulating cruft.
  • Loading branch information
maffoo authored Jul 15, 2022
1 parent ffdb245 commit bc1e2d3
Show file tree
Hide file tree
Showing 66 changed files with 127 additions and 181 deletions.
2 changes: 1 addition & 1 deletion cirq-aqt/cirq_aqt/aqt_device_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

def aqt_device(chain_length: int, use_timedelta=False) -> cad.AQTDevice:
ms = 1000 * cirq.Duration(nanos=1) if not use_timedelta else timedelta(microseconds=1)
return cad.AQTDevice( # type: ignore
return cad.AQTDevice(
measurement_duration=100 * ms, # type: ignore
twoq_gates_duration=200 * ms, # type: ignore
oneq_gates_duration=10 * ms, # type: ignore
Expand Down
10 changes: 5 additions & 5 deletions cirq-core/cirq/_compat_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ class BadlyDeprecatedClass(NewClass):


def _from_parent_import_deprecated():
from cirq.testing._compat_test_data import fake_a # type: ignore
from cirq.testing._compat_test_data import fake_a

assert fake_a.MODULE_A_ATTRIBUTE == 'module_a'

Expand All @@ -379,7 +379,7 @@ def _import_deprecated_assert_sub():


def _from_deprecated_import_sub():
from cirq.testing._compat_test_data.fake_a import module_b # type: ignore
from cirq.testing._compat_test_data.fake_a import module_b

assert module_b.MODULE_B_ATTRIBUTE == 'module_b'

Expand Down Expand Up @@ -450,7 +450,7 @@ def _import_multiple_deprecated():
from cirq.testing._compat_test_data.module_a.module_b import module_c

assert module_c.MODULE_C_ATTRIBUTE == 'module_c'
from cirq.testing._compat_test_data.fake_a.module_b import module_c # type: ignore
from cirq.testing._compat_test_data.fake_a.module_b import module_c

assert module_c.MODULE_C_ATTRIBUTE == 'module_c'
from cirq.testing._compat_test_data.fake_b import module_c # type: ignore
Expand Down Expand Up @@ -531,7 +531,7 @@ def _repeated_import_path():

# pylint: disable=line-too-long
from cirq.testing._compat_test_data.repeated_child.cirq.testing._compat_test_data.repeated_child import ( # type: ignore
child, # type: ignore
child,
)

assert child.CHILD_ATTRIBUTE == 'child'
Expand Down Expand Up @@ -798,7 +798,7 @@ def _test_broken_module_2_inner():
match="missing_module cannot be imported. The typical reasons",
):
# note that this passes
from cirq.testing._compat_test_data import broken_ref # type: ignore
from cirq.testing._compat_test_data import broken_ref

# but when you try to use it
broken_ref.something()
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/circuits/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -2073,7 +2073,7 @@ def insert(
self._moments.insert(k, moment_or_op)
k += 1
else:
op = cast(ops.Operation, moment_or_op)
op = moment_or_op
p = self._pick_or_create_inserted_op_moment_index(k, op, strategy)
while p >= len(self._moments):
self._moments.append(Moment())
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/contrib/qcircuit/qcircuit_diagram_info.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 cast, Optional, Tuple
from typing import Optional, Tuple

from cirq import ops, protocols

Expand Down Expand Up @@ -59,7 +59,7 @@ def hardcoded_qcircuit_diagram_info(op: ops.Operation) -> Optional[protocols.Cir
if isinstance(op.gate, ops.MeasurementGate)
else ()
)
return protocols.CircuitDiagramInfo(cast(Tuple[str, ...], symbols)) if symbols else None
return protocols.CircuitDiagramInfo(symbols) if symbols else None


def convert_text_diagram_info_to_qcircuit_diagram_info(
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/contrib/quantum_volume/quantum_volume.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"""

from dataclasses import dataclass
from typing import Optional, List, cast, Callable, Dict, Tuple, Set, Any
from typing import Optional, List, Callable, Dict, Tuple, Set, Any

import networkx as nx
import numpy as np
Expand Down Expand Up @@ -75,7 +75,7 @@ def compute_heavy_set(circuit: cirq.Circuit) -> List[int]:
# Classically compute the probabilities of each output bit-string through
# simulation.
simulator = cirq.Simulator()
results = cast(cirq.StateVectorTrialResult, simulator.simulate(program=circuit))
results = simulator.simulate(program=circuit)

# Compute the median probability of the output bit-strings. Note that heavy
# output is defined in terms of probabilities, where our wave function is in
Expand Down
1 change: 0 additions & 1 deletion cirq-core/cirq/contrib/svg/svg.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,6 @@ def tdd_to_svg(
t += f'<line x1="{x}" x2="{x}" y1="{y1}" y2="{y2}" stroke="black" stroke-width="3" />'

for (xi, yi), v in tdd.entries.items():
xi = cast(int, xi)
yi = yi_map[yi]

x = col_starts[xi] + col_widths[xi] / 2
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/devices/grid_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
if TYPE_CHECKING:
import cirq

TSelf = TypeVar('TSelf', bound='_BaseGridQid') # type: ignore
TSelf = TypeVar('TSelf', bound='_BaseGridQid')


@functools.total_ordering # type: ignore
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/devices/line_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
if TYPE_CHECKING:
import cirq

TSelf = TypeVar('TSelf', bound='_BaseLineQid') # type: ignore
TSelf = TypeVar('TSelf', bound='_BaseLineQid')


@functools.total_ordering # type: ignore
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/devices/noise_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ def noisy_moment(

NOISE_MODEL_LIKE = Union[None, 'cirq.NoiseModel', 'cirq.Gate']
document(
NOISE_MODEL_LIKE, # type: ignore
NOISE_MODEL_LIKE,
"""A `cirq.NoiseModel` or a value that can be trivially converted into one.
`None` is a `NOISE_MODEL_LIKE`. It will be replaced by the `cirq.NO_NOISE`
Expand Down
7 changes: 2 additions & 5 deletions cirq-core/cirq/interop/quirk/cells/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def apply(op: Union[str, _HangingNode]) -> None:
a = vals.pop()
# Note: vals seems to be _HangingToken
# func operates on _ResolvedTokens. Ignoring type issues for now.
vals.append(cast(_HangingNode, op).func(a, b)) # type: ignore[arg-type]
vals.append(op.func(a, b)) # type: ignore[arg-type]

def close_paren() -> None:
while True:
Expand All @@ -176,10 +176,7 @@ def feed_op(could_be_binary: bool, token: Any) -> None:
# Implied multiplication?
mul = cast(_CustomQuirkOperationToken, token_map["*"])
if could_be_binary and token != ")":
if (
not isinstance(token, _CustomQuirkOperationToken)
or cast(_CustomQuirkOperationToken, token).binary_action is None
):
if not isinstance(token, _CustomQuirkOperationToken) or token.binary_action is None:
burn_ops(mul.priority)
ops.append(
_HangingNode(
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/interop/quirk/url_to_circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def msg(error):

# Remap qubits if requested.
if qubits is not None:
qs = cast(Sequence['cirq.Qid'], qubits)
qs = qubits

def map_qubit(qubit: 'cirq.Qid') -> 'cirq.Qid':
q = cast(devices.LineQubit, qubit)
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/json_resolver_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,13 +232,13 @@ def _symmetricalqidpair(qids):
# pylint: disable=line-too-long
'XEBPhasedFSimCharacterizationOptions': cirq.experiments.XEBPhasedFSimCharacterizationOptions,
# pylint: enable=line-too-long
'_XEigenState': cirq.value.product_state._XEigenState, # type: ignore
'_XEigenState': cirq.value.product_state._XEigenState,
'XPowGate': cirq.XPowGate,
'XXPowGate': cirq.XXPowGate,
'_YEigenState': cirq.value.product_state._YEigenState, # type: ignore
'_YEigenState': cirq.value.product_state._YEigenState,
'YPowGate': cirq.YPowGate,
'YYPowGate': cirq.YYPowGate,
'_ZEigenState': cirq.value.product_state._ZEigenState, # type: ignore
'_ZEigenState': cirq.value.product_state._ZEigenState,
'Zip': cirq.Zip,
'ZPowGate': cirq.ZPowGate,
'ZZPowGate': cirq.ZZPowGate,
Expand Down
3 changes: 1 addition & 2 deletions cirq-core/cirq/ops/classically_controlled_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
AbstractSet,
Any,
Mapping,
cast,
Dict,
FrozenSet,
List,
Expand Down Expand Up @@ -85,7 +84,7 @@ def __init__(
c = value.KeyCondition(c)
if isinstance(c, sympy.Basic):
c = value.SympyCondition(c)
conds.append(cast('cirq.Condition', c))
conds.append(c)
self._conditions: Tuple['cirq.Condition', ...] = tuple(conds)
self._sub_operation: 'cirq.Operation' = sub_operation

Expand Down
8 changes: 3 additions & 5 deletions cirq-core/cirq/ops/clifford_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, cast, Dict, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union
from typing import Any, Dict, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union


import numpy as np
Expand Down Expand Up @@ -90,7 +90,7 @@ def _validate_map_input(
) -> Dict[Pauli, Tuple[Pauli, bool]]:
if pauli_map_to is None:
xyz_to = {pauli_gates.X: x_to, pauli_gates.Y: y_to, pauli_gates.Z: z_to}
pauli_map_to = {cast(Pauli, p): trans for p, trans in xyz_to.items() if trans is not None}
pauli_map_to = {p: trans for p, trans in xyz_to.items() if trans is not None}
elif x_to is not None or y_to is not None or z_to is not None:
raise ValueError(
'{} can take either pauli_map_to or a combination'
Expand Down Expand Up @@ -531,9 +531,7 @@ def from_single_map(
trans_to2 = trans_from
flip2 = not flip
rotation_map[trans_from2] = (trans_to2, flip2)
return SingleQubitCliffordGate.from_double_map(
cast(Dict[Pauli, Tuple[Pauli, bool]], rotation_map)
)
return SingleQubitCliffordGate.from_double_map(rotation_map)

@staticmethod
def from_double_map(
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/common_gate_families.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def __init__(
if isinstance(gate, parallel_gate.ParallelGate):
if not max_parallel_allowed:
max_parallel_allowed = protocols.num_qubits(gate)
gate = cast(parallel_gate.ParallelGate, gate).sub_gate
gate = gate.sub_gate
self._max_parallel_allowed = max_parallel_allowed
super().__init__(gate, name=name, description=description)

Expand Down
4 changes: 1 addition & 3 deletions cirq-core/cirq/ops/control_values.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.
import abc
from typing import Union, Tuple, List, TYPE_CHECKING, Any, Dict, Generator, cast, Iterator, Optional
from typing import Union, Tuple, List, TYPE_CHECKING, Any, Dict, Generator, Iterator, Optional
from dataclasses import dataclass

import itertools
Expand Down Expand Up @@ -121,7 +121,6 @@ def _identifier(self) -> Tuple[Tuple[int, ...], ...]:

def _expand(self) -> Iterator[Tuple[int, ...]]:
"""Returns the combinations tracked by the object."""
self = cast('ProductOfSums', self)
return itertools.product(*self._internal_representation)

def __repr__(self) -> str:
Expand Down Expand Up @@ -231,7 +230,6 @@ def _identifier(self) -> Tuple[Tuple[int, ...], ...]:

def _expand(self) -> Iterator[Tuple[int, ...]]:
"""Returns the combinations tracked by the object."""
self = cast('SumOfProducts', self)
return iter(self._internal_representation)

def __repr__(self) -> str:
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/controlled_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def __init__(

# Flatten nested ControlledGates.
if isinstance(sub_gate, ControlledGate):
self._sub_gate = sub_gate.sub_gate # type: ignore
self._sub_gate = sub_gate.sub_gate
self._control_values = self._control_values & sub_gate.control_values
self._control_qid_shape += sub_gate.control_qid_shape
else:
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 @@ -50,7 +50,7 @@
int, float, complex, PauliString, 'PauliSum', pauli_string.SingleQubitPauliStringGateOperation
]
document(
PauliSumLike, # type: ignore
PauliSumLike,
"""Any value that can be easily translated into a sum of Pauli products.
""",
)
Expand Down
5 changes: 2 additions & 3 deletions cirq-core/cirq/ops/matrix_gates.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

"""Quantum gates defined by a matrix."""

from typing import Any, cast, Dict, Iterable, Optional, Tuple, TYPE_CHECKING
from typing import Any, Dict, Iterable, Optional, Tuple, TYPE_CHECKING

import numpy as np

Expand Down Expand Up @@ -115,8 +115,7 @@ def _qid_shape_(self) -> Tuple[int, ...]:
def __pow__(self, exponent: Any) -> 'MatrixGate':
if not isinstance(exponent, (int, float)):
return NotImplemented
e = cast(float, exponent)
new_mat = linalg.map_eigenvalues(self._matrix, lambda b: b**e)
new_mat = linalg.map_eigenvalues(self._matrix, lambda b: b**exponent)
return MatrixGate(new_mat, qid_shape=self._qid_shape)

def _phase_by_(self, phase_turns: float, qubit_index: int) -> 'MatrixGate':
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/named_qubit.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
if TYPE_CHECKING:
import cirq

TSelf = TypeVar('TSelf', bound='_BaseNamedQid') # type: ignore
TSelf = TypeVar('TSelf', bound='_BaseNamedQid')


@functools.total_ordering # type: ignore
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/op_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def __iter__(self) -> Iterator[Union[Operation, 'OpTree']]:

OP_TREE = Union[Operation, OpTree]
document(
OP_TREE, # type: ignore
OP_TREE,
"""An operation or nested collections of operations.
Here are some examples of things that can be given to a method that takes a
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/ops/pauli_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
Iterable, # of PAULI_STRING_LIKE, but mypy doesn't do recursive types yet.
]
document(
PAULI_STRING_LIKE, # type: ignore
PAULI_STRING_LIKE,
"""A `cirq.PauliString` or a value that can easily be converted into one.
Complex numbers turn into the coefficient of an empty Pauli string.
Expand All @@ -94,7 +94,7 @@

PAULI_GATE_LIKE = Union['cirq.Pauli', 'cirq.IdentityGate', str, int,]
document(
PAULI_GATE_LIKE, # type: ignore
PAULI_GATE_LIKE,
"""An object that can be interpreted as a Pauli gate.
Allowed values are:
Expand Down Expand Up @@ -1715,4 +1715,4 @@ def _pauli_like_to_pauli_int(key: Any, pauli_gate_like: PAULI_GATE_LIKE):
f"But the value isn't in "
f"{set(PAULI_GATE_LIKE_TO_INDEX_MAP.keys())!r}"
)
return cast(int, pauli_int)
return pauli_int
12 changes: 3 additions & 9 deletions cirq-core/cirq/ops/pauli_string_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import itertools
import math
from typing import List, cast
from typing import List

import numpy as np
import pytest
Expand Down Expand Up @@ -656,10 +656,7 @@ def _assert_pass_over(ops: List[cirq.Operation], before: cirq.PauliString, after
@pytest.mark.parametrize('shift,sign', itertools.product(range(3), (-1, +1)))
def test_pass_operations_over_single(shift: int, sign: int):
q0, q1 = _make_qubits(2)
X, Y, Z = (
cirq.Pauli.by_relative_index(cast(cirq.Pauli, pauli), shift)
for pauli in (cirq.X, cirq.Y, cirq.Z)
)
X, Y, Z = (cirq.Pauli.by_relative_index(pauli, shift) for pauli in (cirq.X, cirq.Y, cirq.Z))

op0 = cirq.SingleQubitCliffordGate.from_pauli(Y)(q1)
ps_before: cirq.PauliString[cirq.Qid] = cirq.PauliString({q0: X}, sign)
Expand Down Expand Up @@ -698,10 +695,7 @@ def test_pass_operations_over_single(shift: int, sign: int):
def test_pass_operations_over_double(shift: int, t_or_f1: bool, t_or_f2: bool, neg: bool):
sign = -1 if neg else +1
q0, q1, q2 = _make_qubits(3)
X, Y, Z = (
cirq.Pauli.by_relative_index(cast(cirq.Pauli, pauli), shift)
for pauli in (cirq.X, cirq.Y, cirq.Z)
)
X, Y, Z = (cirq.Pauli.by_relative_index(pauli, shift) for pauli in (cirq.X, cirq.Y, cirq.Z))

op0 = cirq.PauliInteractionGate(Z, t_or_f1, X, t_or_f2)(q0, q1)
ps_before = cirq.PauliString(qubit_pauli_map={q0: Z, q2: Y}, coefficient=sign)
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/qubit_order_or_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

QubitOrderOrList = Union[qubit_order.QubitOrder, Iterable[raw_types.Qid]]
document(
QubitOrderOrList, # type: ignore
QubitOrderOrList,
"""Specifies a qubit ordering.
The ordering can either be specified by an iterable (such as a list) with
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/protocols/json_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -729,7 +729,7 @@ def to_json_gzip(
actually_a_file.write(json_str)
return None

gzip_data = gzip.compress(bytes(json_str, encoding='utf-8')) # type: ignore
gzip_data = gzip.compress(bytes(json_str, encoding='utf-8'))
if file_or_fn is None:
return gzip_data

Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/protocols/json_serialization_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def _get_testspecs_for_modules() -> List[ModuleJsonTestSpec]:
def test_deprecated_cirq_type_in_json_dict():
class HasOldJsonDict:
# Required for testing serialization of non-cirq objects.
__module__ = 'test.noncirq.namespace' # type: ignore
__module__ = 'test.noncirq.namespace'

def __eq__(self, other):
return isinstance(other, HasOldJsonDict)
Expand Down
Loading

0 comments on commit bc1e2d3

Please sign in to comment.