Skip to content

Commit

Permalink
Update to mypy 1.2 (#6059)
Browse files Browse the repository at this point in the history
Review: @viathor
  • Loading branch information
maffoo committed Apr 13, 2023
1 parent 6a5b3ea commit e7ef9d4
Show file tree
Hide file tree
Showing 99 changed files with 386 additions and 360 deletions.
6 changes: 3 additions & 3 deletions cirq-core/cirq/_compat_test.py
Expand Up @@ -98,7 +98,7 @@ def test_proper_repr_data_frame():
pd.testing.assert_frame_equal(df2, df)


def test_dataclass_repr_simple():
def test_dataclass_repr_simple() -> None:
@dataclasses.dataclass
class TestClass1:
x: int
Expand All @@ -111,7 +111,7 @@ def __repr__(self):
assert repr(TestClass1(5, 'hi')) == "cirq.TestClass1(x=5, y='hi')"


def test_dataclass_repr_numpy():
def test_dataclass_repr_numpy() -> None:
@dataclasses.dataclass
class TestClass2:
x: np.ndarray
Expand Down Expand Up @@ -1003,7 +1003,7 @@ def bar(self):


class Bar:
def __init__(self):
def __init__(self) -> None:
self.foo_calls: Dict[int, int] = collections.Counter()
self.bar_calls: Dict[int, int] = collections.Counter()

Expand Down
16 changes: 12 additions & 4 deletions cirq-core/cirq/circuits/circuit.py
Expand Up @@ -305,7 +305,10 @@ def _first_moment_operating_on(
return None

def next_moment_operating_on(
self, qubits: Iterable['cirq.Qid'], start_moment_index: int = 0, max_distance: int = None
self,
qubits: Iterable['cirq.Qid'],
start_moment_index: int = 0,
max_distance: Optional[int] = None,
) -> Optional[int]:
"""Finds the index of the next moment that touches the given qubits.
Expand Down Expand Up @@ -2128,7 +2131,7 @@ def _push_frontier(
self,
early_frontier: Dict['cirq.Qid', int],
late_frontier: Dict['cirq.Qid', int],
update_qubits: Iterable['cirq.Qid'] = None,
update_qubits: Optional[Iterable['cirq.Qid']] = None,
) -> Tuple[int, int]:
"""Inserts moments to separate two frontiers.
Expand Down Expand Up @@ -2198,7 +2201,10 @@ def _insert_operations(
)

def insert_at_frontier(
self, operations: 'cirq.OP_TREE', start: int, frontier: Dict['cirq.Qid', int] = None
self,
operations: 'cirq.OP_TREE',
start: int,
frontier: Optional[Dict['cirq.Qid', int]] = None,
) -> Dict['cirq.Qid', int]:
"""Inserts operations inline at frontier.
Expand Down Expand Up @@ -2389,7 +2395,9 @@ def with_noise(self, noise: 'cirq.NOISE_MODEL_LIKE') -> 'cirq.Circuit':


def _pick_inserted_ops_moment_indices(
operations: Sequence['cirq.Operation'], start: int = 0, frontier: Dict['cirq.Qid', int] = None
operations: Sequence['cirq.Operation'],
start: int = 0,
frontier: Optional[Dict['cirq.Qid', int]] = None,
) -> Tuple[Sequence[int], Dict['cirq.Qid', int]]:
"""Greedily assigns operations to moments.
Expand Down
8 changes: 4 additions & 4 deletions cirq-core/cirq/circuits/circuit_operation_test.py
Expand Up @@ -274,7 +274,7 @@ def test_recursive_params():

@pytest.mark.parametrize('add_measurements', [True, False])
@pytest.mark.parametrize('use_default_ids_for_initial_rep', [True, False])
def test_repeat(add_measurements, use_default_ids_for_initial_rep):
def test_repeat(add_measurements: bool, use_default_ids_for_initial_rep: bool) -> None:
a, b = cirq.LineQubit.range(2)
circuit = cirq.Circuit(cirq.H(a), cirq.CX(a, b))
if add_measurements:
Expand Down Expand Up @@ -327,9 +327,9 @@ def test_repeat(add_measurements, use_default_ids_for_initial_rep):
_ = op_base.repeat()

with pytest.raises(TypeError, match='Only integer or sympy repetitions are allowed'):
_ = op_base.repeat(1.3)
assert op_base.repeat(3.00000000001).repetitions == 3
assert op_base.repeat(2.99999999999).repetitions == 3
_ = op_base.repeat(1.3) # type: ignore[arg-type]
assert op_base.repeat(3.00000000001).repetitions == 3 # type: ignore[arg-type]
assert op_base.repeat(2.99999999999).repetitions == 3 # type: ignore[arg-type]


@pytest.mark.parametrize('add_measurements', [True, False])
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/circuits/text_diagram_drawer.py
Expand Up @@ -292,7 +292,7 @@ def render(
self,
horizontal_spacing: int = 1,
vertical_spacing: int = 1,
crossing_char: str = None,
crossing_char: Optional[str] = None,
use_unicode_characters: bool = True,
) -> str:
"""Outputs text containing the diagram."""
Expand Down
5 changes: 4 additions & 1 deletion cirq-core/cirq/contrib/acquaintance/executor.py
Expand Up @@ -174,7 +174,10 @@ class GreedyExecutionStrategy(ExecutionStrategy):
"""

def __init__(
self, gates: LogicalGates, initial_mapping: LogicalMapping, device: 'cirq.Device' = None
self,
gates: LogicalGates,
initial_mapping: LogicalMapping,
device: Optional['cirq.Device'] = None,
) -> None:
"""Inits GreedyExecutionStrategy.
Expand Down
15 changes: 13 additions & 2 deletions cirq-core/cirq/contrib/acquaintance/permutation.py
Expand Up @@ -13,7 +13,18 @@
# limitations under the License.

import abc
from typing import Any, cast, Dict, Iterable, Sequence, Tuple, TypeVar, Union, TYPE_CHECKING
from typing import (
Any,
cast,
Dict,
Iterable,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
TYPE_CHECKING,
)

from cirq import circuits, ops, protocols, transformers, value
from cirq.type_workarounds import NotImplementedType
Expand Down Expand Up @@ -72,7 +83,7 @@ def update_mapping(
mapping[new_key] = old_element

@staticmethod
def validate_permutation(permutation: Dict[int, int], n_elements: int = None) -> None:
def validate_permutation(permutation: Dict[int, int], n_elements: Optional[int] = None) -> None:
if not permutation:
return
if set(permutation.values()) != set(permutation):
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/contrib/qasm_import/_parser.py
Expand Up @@ -141,7 +141,7 @@ class QasmParser:
parsedQasm = QasmParser().parse(qasm)
"""

def __init__(self):
def __init__(self) -> None:
self.parser = yacc.yacc(module=self, debug=False, write_tables=False)
self.circuit = Circuit()
self.qregs: Dict[str, int] = {}
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/contrib/quantum_volume/quantum_volume.py
Expand Up @@ -200,7 +200,7 @@ def compile_circuit(
*,
device_graph: nx.Graph,
routing_attempts: int,
compiler: Callable[[cirq.Circuit], cirq.Circuit] = None,
compiler: Optional[Callable[[cirq.Circuit], cirq.Circuit]] = None,
routing_algo_name: Optional[str] = None,
router: Optional[Callable[..., ccr.SwapNetwork]] = None,
add_readout_error_correction=False,
Expand Down Expand Up @@ -357,7 +357,7 @@ def execute_circuits(
samplers: List[cirq.Sampler],
circuits: List[Tuple[cirq.Circuit, List[int]]],
routing_attempts: int,
compiler: Callable[[cirq.Circuit], cirq.Circuit] = None,
compiler: Optional[Callable[[cirq.Circuit], cirq.Circuit]] = None,
repetitions: int = 10_000,
add_readout_error_correction=False,
) -> List[QuantumVolumeResult]:
Expand Down Expand Up @@ -429,7 +429,7 @@ def calculate_quantum_volume(
device_graph: nx.Graph,
samplers: List[cirq.Sampler],
random_state: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,
compiler: Callable[[cirq.Circuit], cirq.Circuit] = None,
compiler: Optional[Callable[[cirq.Circuit], cirq.Circuit]] = None,
repetitions=10_000,
routing_attempts=30,
add_readout_error_correction=False,
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/contrib/quimb/mps_simulator.py
Expand Up @@ -569,7 +569,7 @@ def __init__(
simulation_options: MPSOptions = MPSOptions(),
grouping: Optional[Dict['cirq.Qid', int]] = None,
initial_state: int = 0,
classical_data: 'cirq.ClassicalDataStore' = None,
classical_data: Optional['cirq.ClassicalDataStore'] = None,
):
"""Creates and MPSState
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/contrib/svg/svg_test.py
@@ -1,5 +1,5 @@
# pylint: disable=wrong-or-nonexistent-copyright-notice
import IPython.display # type: ignore
import IPython.display # type: ignore[import]
import numpy as np
import pytest

Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/devices/grid_qubit.py
Expand Up @@ -27,7 +27,7 @@
TSelf = TypeVar('TSelf', bound='_BaseGridQid')


@functools.total_ordering # type: ignore
@functools.total_ordering
class _BaseGridQid(ops.Qid):
"""The Base class for `GridQid` and `GridQubit`."""

Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/devices/line_qubit.py
Expand Up @@ -25,7 +25,7 @@
TSelf = TypeVar('TSelf', bound='_BaseLineQid')


@functools.total_ordering # type: ignore
@functools.total_ordering
class _BaseLineQid(ops.Qid):
"""The base class for `LineQid` and `LineQubit`."""

Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/devices/named_topologies.py
Expand Up @@ -345,7 +345,7 @@ def draw_placements(
small_graph: nx.Graph,
small_to_big_mappings: Sequence[Dict],
max_plots: int = 20,
axes: Sequence[plt.Axes] = None,
axes: Optional[Sequence[plt.Axes]] = None,
tilted: bool = True,
bad_placement_callback: Optional[Callable[[plt.Axes, int], None]] = None,
):
Expand Down
3 changes: 3 additions & 0 deletions cirq-core/cirq/devices/noise_model.py
Expand Up @@ -125,6 +125,7 @@ def noisy_moments(
A sequence of OP_TREEs, with the k'th tree corresponding to the
noisy operations for the k'th moment.
"""
raise NotImplementedError

def _noisy_moment_impl_moments(
self, moment: 'cirq.Moment', system_qubits: Sequence['cirq.Qid']
Expand All @@ -150,6 +151,7 @@ def noisy_moment(
Returns:
An OP_TREE corresponding to the noisy operations for the moment.
"""
raise NotImplementedError

def _noisy_operation_impl_moments(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE':
return self.noisy_moments([moment_module.Moment([operation])], operation.qubits)
Expand All @@ -169,6 +171,7 @@ def noisy_operation(self, operation: 'cirq.Operation') -> 'cirq.OP_TREE':
An OP_TREE corresponding to the noisy operations implementing the
noisy version of the given operation.
"""
raise NotImplementedError


@value.value_equality
Expand Down
Expand Up @@ -27,9 +27,7 @@


# TODO: missing per-device defaults
# Type-ignored because mypy cannot handle abstract dataclasses:
# https://github.com/python/mypy/issues/5374
@dataclass # type: ignore
@dataclass
class SuperconductingQubitsNoiseProperties(devices.NoiseProperties, abc.ABC):
"""Noise-defining properties for a superconducting-qubit-based device.
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/experiments/n_qubit_tomography.py
Expand Up @@ -134,7 +134,7 @@ def state_tomography(
qubits: Sequence['cirq.Qid'],
circuit: 'cirq.Circuit',
repetitions: int = 1000,
prerotations: Sequence[Tuple[float, float]] = None,
prerotations: Optional[Sequence[Tuple[float, float]]] = None,
) -> TomographyResult:
"""This performs n qubit tomography on a cirq circuit
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/experiments/qubit_characterizations.py
Expand Up @@ -542,8 +542,8 @@ def _matrix_bar_plot(
mat: np.ndarray,
z_label: str,
ax: plt.Axes,
kets: Sequence[str] = None,
title: str = None,
kets: Optional[Sequence[str]] = None,
title: Optional[str] = None,
ylim: Tuple[int, int] = (-1, 1),
**bar3d_kwargs: Any,
) -> None:
Expand Down
Expand Up @@ -111,7 +111,7 @@ def estimate_parallel_single_qubit_readout_errors(
trials: int = 20,
repetitions: int = 1000,
trials_per_batch: Optional[int] = None,
bit_strings: np.ndarray = None,
bit_strings: Optional[np.ndarray] = None,
) -> SingleQubitReadoutCalibrationResult:
"""Estimate single qubit readout error using parallel operations.
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/experiments/t2_decay_experiment.py
Expand Up @@ -45,7 +45,7 @@ def t2_decay(
min_delay: 'cirq.DURATION_LIKE' = None,
repetitions: int = 1000,
delay_sweep: Optional[study.Sweep] = None,
num_pulses: List[int] = None,
num_pulses: Optional[List[int]] = None,
) -> Union['cirq.experiments.T2DecayResult', List['cirq.experiments.T2DecayResult']]:
"""Runs a t2 transverse relaxation experiment.
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/interop/quirk/cells/testing.py
Expand Up @@ -22,7 +22,7 @@

def assert_url_to_circuit_returns(
json_text: str,
circuit: 'cirq.Circuit' = None,
circuit: Optional['cirq.Circuit'] = None,
*,
unitary: Optional[np.ndarray] = None,
diagram: Optional[str] = None,
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/linalg/transformations.py
Expand Up @@ -249,7 +249,7 @@ def targeted_conjugate_about(
tensor: np.ndarray,
target: np.ndarray,
indices: Sequence[int],
conj_indices: Sequence[int] = None,
conj_indices: Optional[Sequence[int]] = None,
buffer: Optional[np.ndarray] = None,
out: Optional[np.ndarray] = None,
) -> np.ndarray:
Expand Down
6 changes: 0 additions & 6 deletions cirq-core/cirq/ops/clifford_gate.py
Expand Up @@ -75,12 +75,6 @@ def _to_clifford_tableau(
return clifford_tableau


def _pretend_initialized() -> 'SingleQubitCliffordGate':
# HACK: This is a workaround to fool mypy and pylint into correctly handling
# class fields that can't be initialized until after the class is defined.
pass


def _validate_map_input(
required_transform_count: int,
pauli_map_to: Optional[Dict[Pauli, Tuple[Pauli, bool]]],
Expand Down
8 changes: 4 additions & 4 deletions cirq-core/cirq/ops/common_gates.py
Expand Up @@ -187,7 +187,7 @@ def _trace_distance_bound_(self) -> Optional[float]:

def controlled(
self,
num_controls: int = None,
num_controls: Optional[int] = None,
control_values: Optional[
Union[cv.AbstractControlValues, Sequence[Union[int, Collection[int]]]]
] = None,
Expand Down Expand Up @@ -667,7 +667,7 @@ def with_canonical_global_phase(self) -> 'ZPowGate':

def controlled(
self,
num_controls: int = None,
num_controls: Optional[int] = None,
control_values: Optional[
Union[cv.AbstractControlValues, Sequence[Union[int, Collection[int]]]]
] = None,
Expand Down Expand Up @@ -1122,7 +1122,7 @@ def _phase_by_(self, phase_turns, qubit_index):

def controlled(
self,
num_controls: int = None,
num_controls: Optional[int] = None,
control_values: Optional[
Union[cv.AbstractControlValues, Sequence[Union[int, Collection[int]]]]
] = None,
Expand Down Expand Up @@ -1328,7 +1328,7 @@ def _pauli_expansion_(self) -> value.LinearDict[str]:

def controlled(
self,
num_controls: int = None,
num_controls: Optional[int] = None,
control_values: Optional[
Union[cv.AbstractControlValues, Sequence[Union[int, Collection[int]]]]
] = None,
Expand Down

0 comments on commit e7ef9d4

Please sign in to comment.