Skip to content

Commit e64897f

Browse files
committed
Update to mypy 1.2
1 parent 920d89f commit e64897f

File tree

99 files changed

+386
-360
lines changed

Some content is hidden

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

99 files changed

+386
-360
lines changed

Diff for: cirq-core/cirq/_compat_test.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def test_proper_repr_data_frame():
9898
pd.testing.assert_frame_equal(df2, df)
9999

100100

101-
def test_dataclass_repr_simple():
101+
def test_dataclass_repr_simple() -> None:
102102
@dataclasses.dataclass
103103
class TestClass1:
104104
x: int
@@ -111,7 +111,7 @@ def __repr__(self):
111111
assert repr(TestClass1(5, 'hi')) == "cirq.TestClass1(x=5, y='hi')"
112112

113113

114-
def test_dataclass_repr_numpy():
114+
def test_dataclass_repr_numpy() -> None:
115115
@dataclasses.dataclass
116116
class TestClass2:
117117
x: np.ndarray
@@ -1003,7 +1003,7 @@ def bar(self):
10031003

10041004

10051005
class Bar:
1006-
def __init__(self):
1006+
def __init__(self) -> None:
10071007
self.foo_calls: Dict[int, int] = collections.Counter()
10081008
self.bar_calls: Dict[int, int] = collections.Counter()
10091009

Diff for: cirq-core/cirq/circuits/circuit.py

+12-4
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,10 @@ def _first_moment_operating_on(
305305
return None
306306

307307
def next_moment_operating_on(
308-
self, qubits: Iterable['cirq.Qid'], start_moment_index: int = 0, max_distance: int = None
308+
self,
309+
qubits: Iterable['cirq.Qid'],
310+
start_moment_index: int = 0,
311+
max_distance: Optional[int] = None,
309312
) -> Optional[int]:
310313
"""Finds the index of the next moment that touches the given qubits.
311314
@@ -2128,7 +2131,7 @@ def _push_frontier(
21282131
self,
21292132
early_frontier: Dict['cirq.Qid', int],
21302133
late_frontier: Dict['cirq.Qid', int],
2131-
update_qubits: Iterable['cirq.Qid'] = None,
2134+
update_qubits: Optional[Iterable['cirq.Qid']] = None,
21322135
) -> Tuple[int, int]:
21332136
"""Inserts moments to separate two frontiers.
21342137
@@ -2198,7 +2201,10 @@ def _insert_operations(
21982201
)
21992202

22002203
def insert_at_frontier(
2201-
self, operations: 'cirq.OP_TREE', start: int, frontier: Dict['cirq.Qid', int] = None
2204+
self,
2205+
operations: 'cirq.OP_TREE',
2206+
start: int,
2207+
frontier: Optional[Dict['cirq.Qid', int]] = None,
22022208
) -> Dict['cirq.Qid', int]:
22032209
"""Inserts operations inline at frontier.
22042210
@@ -2389,7 +2395,9 @@ def with_noise(self, noise: 'cirq.NOISE_MODEL_LIKE') -> 'cirq.Circuit':
23892395

23902396

23912397
def _pick_inserted_ops_moment_indices(
2392-
operations: Sequence['cirq.Operation'], start: int = 0, frontier: Dict['cirq.Qid', int] = None
2398+
operations: Sequence['cirq.Operation'],
2399+
start: int = 0,
2400+
frontier: Optional[Dict['cirq.Qid', int]] = None,
23932401
) -> Tuple[Sequence[int], Dict['cirq.Qid', int]]:
23942402
"""Greedily assigns operations to moments.
23952403

Diff for: cirq-core/cirq/circuits/circuit_operation_test.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ def test_recursive_params():
274274

275275
@pytest.mark.parametrize('add_measurements', [True, False])
276276
@pytest.mark.parametrize('use_default_ids_for_initial_rep', [True, False])
277-
def test_repeat(add_measurements, use_default_ids_for_initial_rep):
277+
def test_repeat(add_measurements: bool, use_default_ids_for_initial_rep: bool) -> None:
278278
a, b = cirq.LineQubit.range(2)
279279
circuit = cirq.Circuit(cirq.H(a), cirq.CX(a, b))
280280
if add_measurements:
@@ -327,9 +327,9 @@ def test_repeat(add_measurements, use_default_ids_for_initial_rep):
327327
_ = op_base.repeat()
328328

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

334334

335335
@pytest.mark.parametrize('add_measurements', [True, False])

Diff for: cirq-core/cirq/circuits/text_diagram_drawer.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ def render(
292292
self,
293293
horizontal_spacing: int = 1,
294294
vertical_spacing: int = 1,
295-
crossing_char: str = None,
295+
crossing_char: Optional[str] = None,
296296
use_unicode_characters: bool = True,
297297
) -> str:
298298
"""Outputs text containing the diagram."""

Diff for: cirq-core/cirq/contrib/acquaintance/executor.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,10 @@ class GreedyExecutionStrategy(ExecutionStrategy):
174174
"""
175175

176176
def __init__(
177-
self, gates: LogicalGates, initial_mapping: LogicalMapping, device: 'cirq.Device' = None
177+
self,
178+
gates: LogicalGates,
179+
initial_mapping: LogicalMapping,
180+
device: Optional['cirq.Device'] = None,
178181
) -> None:
179182
"""Inits GreedyExecutionStrategy.
180183

Diff for: cirq-core/cirq/contrib/acquaintance/permutation.py

+13-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,18 @@
1313
# limitations under the License.
1414

1515
import abc
16-
from typing import Any, cast, Dict, Iterable, Sequence, Tuple, TypeVar, Union, TYPE_CHECKING
16+
from typing import (
17+
Any,
18+
cast,
19+
Dict,
20+
Iterable,
21+
Optional,
22+
Sequence,
23+
Tuple,
24+
TypeVar,
25+
Union,
26+
TYPE_CHECKING,
27+
)
1728

1829
from cirq import circuits, ops, protocols, transformers, value
1930
from cirq.type_workarounds import NotImplementedType
@@ -72,7 +83,7 @@ def update_mapping(
7283
mapping[new_key] = old_element
7384

7485
@staticmethod
75-
def validate_permutation(permutation: Dict[int, int], n_elements: int = None) -> None:
86+
def validate_permutation(permutation: Dict[int, int], n_elements: Optional[int] = None) -> None:
7687
if not permutation:
7788
return
7889
if set(permutation.values()) != set(permutation):

Diff for: cirq-core/cirq/contrib/qasm_import/_parser.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ class QasmParser:
141141
parsedQasm = QasmParser().parse(qasm)
142142
"""
143143

144-
def __init__(self):
144+
def __init__(self) -> None:
145145
self.parser = yacc.yacc(module=self, debug=False, write_tables=False)
146146
self.circuit = Circuit()
147147
self.qregs: Dict[str, int] = {}

Diff for: cirq-core/cirq/contrib/quantum_volume/quantum_volume.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ def compile_circuit(
200200
*,
201201
device_graph: nx.Graph,
202202
routing_attempts: int,
203-
compiler: Callable[[cirq.Circuit], cirq.Circuit] = None,
203+
compiler: Optional[Callable[[cirq.Circuit], cirq.Circuit]] = None,
204204
routing_algo_name: Optional[str] = None,
205205
router: Optional[Callable[..., ccr.SwapNetwork]] = None,
206206
add_readout_error_correction=False,
@@ -357,7 +357,7 @@ def execute_circuits(
357357
samplers: List[cirq.Sampler],
358358
circuits: List[Tuple[cirq.Circuit, List[int]]],
359359
routing_attempts: int,
360-
compiler: Callable[[cirq.Circuit], cirq.Circuit] = None,
360+
compiler: Optional[Callable[[cirq.Circuit], cirq.Circuit]] = None,
361361
repetitions: int = 10_000,
362362
add_readout_error_correction=False,
363363
) -> List[QuantumVolumeResult]:
@@ -429,7 +429,7 @@ def calculate_quantum_volume(
429429
device_graph: nx.Graph,
430430
samplers: List[cirq.Sampler],
431431
random_state: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None,
432-
compiler: Callable[[cirq.Circuit], cirq.Circuit] = None,
432+
compiler: Optional[Callable[[cirq.Circuit], cirq.Circuit]] = None,
433433
repetitions=10_000,
434434
routing_attempts=30,
435435
add_readout_error_correction=False,

Diff for: cirq-core/cirq/contrib/quimb/mps_simulator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -569,7 +569,7 @@ def __init__(
569569
simulation_options: MPSOptions = MPSOptions(),
570570
grouping: Optional[Dict['cirq.Qid', int]] = None,
571571
initial_state: int = 0,
572-
classical_data: 'cirq.ClassicalDataStore' = None,
572+
classical_data: Optional['cirq.ClassicalDataStore'] = None,
573573
):
574574
"""Creates and MPSState
575575

Diff for: cirq-core/cirq/contrib/svg/svg_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# pylint: disable=wrong-or-nonexistent-copyright-notice
2-
import IPython.display # type: ignore
2+
import IPython.display # type: ignore[import]
33
import numpy as np
44
import pytest
55

Diff for: cirq-core/cirq/devices/grid_qubit.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
TSelf = TypeVar('TSelf', bound='_BaseGridQid')
2828

2929

30-
@functools.total_ordering # type: ignore
30+
@functools.total_ordering
3131
class _BaseGridQid(ops.Qid):
3232
"""The Base class for `GridQid` and `GridQubit`."""
3333

Diff for: cirq-core/cirq/devices/line_qubit.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
TSelf = TypeVar('TSelf', bound='_BaseLineQid')
2626

2727

28-
@functools.total_ordering # type: ignore
28+
@functools.total_ordering
2929
class _BaseLineQid(ops.Qid):
3030
"""The base class for `LineQid` and `LineQubit`."""
3131

Diff for: cirq-core/cirq/devices/named_topologies.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -345,7 +345,7 @@ def draw_placements(
345345
small_graph: nx.Graph,
346346
small_to_big_mappings: Sequence[Dict],
347347
max_plots: int = 20,
348-
axes: Sequence[plt.Axes] = None,
348+
axes: Optional[Sequence[plt.Axes]] = None,
349349
tilted: bool = True,
350350
bad_placement_callback: Optional[Callable[[plt.Axes, int], None]] = None,
351351
):

Diff for: cirq-core/cirq/devices/noise_model.py

+3
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ def noisy_moments(
125125
A sequence of OP_TREEs, with the k'th tree corresponding to the
126126
noisy operations for the k'th moment.
127127
"""
128+
raise NotImplementedError
128129

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

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

173176

174177
@value.value_equality

Diff for: cirq-core/cirq/devices/superconducting_qubits_noise_properties.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,7 @@
2727

2828

2929
# TODO: missing per-device defaults
30-
# Type-ignored because mypy cannot handle abstract dataclasses:
31-
# https://github.com/python/mypy/issues/5374
32-
@dataclass # type: ignore
30+
@dataclass
3331
class SuperconductingQubitsNoiseProperties(devices.NoiseProperties, abc.ABC):
3432
"""Noise-defining properties for a superconducting-qubit-based device.
3533

Diff for: cirq-core/cirq/experiments/n_qubit_tomography.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ def state_tomography(
134134
qubits: Sequence['cirq.Qid'],
135135
circuit: 'cirq.Circuit',
136136
repetitions: int = 1000,
137-
prerotations: Sequence[Tuple[float, float]] = None,
137+
prerotations: Optional[Sequence[Tuple[float, float]]] = None,
138138
) -> TomographyResult:
139139
"""This performs n qubit tomography on a cirq circuit
140140

Diff for: cirq-core/cirq/experiments/qubit_characterizations.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -542,8 +542,8 @@ def _matrix_bar_plot(
542542
mat: np.ndarray,
543543
z_label: str,
544544
ax: plt.Axes,
545-
kets: Sequence[str] = None,
546-
title: str = None,
545+
kets: Optional[Sequence[str]] = None,
546+
title: Optional[str] = None,
547547
ylim: Tuple[int, int] = (-1, 1),
548548
**bar3d_kwargs: Any,
549549
) -> None:

Diff for: cirq-core/cirq/experiments/single_qubit_readout_calibration.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def estimate_parallel_single_qubit_readout_errors(
111111
trials: int = 20,
112112
repetitions: int = 1000,
113113
trials_per_batch: Optional[int] = None,
114-
bit_strings: np.ndarray = None,
114+
bit_strings: Optional[np.ndarray] = None,
115115
) -> SingleQubitReadoutCalibrationResult:
116116
"""Estimate single qubit readout error using parallel operations.
117117

Diff for: cirq-core/cirq/experiments/t2_decay_experiment.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def t2_decay(
4545
min_delay: 'cirq.DURATION_LIKE' = None,
4646
repetitions: int = 1000,
4747
delay_sweep: Optional[study.Sweep] = None,
48-
num_pulses: List[int] = None,
48+
num_pulses: Optional[List[int]] = None,
4949
) -> Union['cirq.experiments.T2DecayResult', List['cirq.experiments.T2DecayResult']]:
5050
"""Runs a t2 transverse relaxation experiment.
5151

Diff for: cirq-core/cirq/interop/quirk/cells/testing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
def assert_url_to_circuit_returns(
2424
json_text: str,
25-
circuit: 'cirq.Circuit' = None,
25+
circuit: Optional['cirq.Circuit'] = None,
2626
*,
2727
unitary: Optional[np.ndarray] = None,
2828
diagram: Optional[str] = None,

Diff for: cirq-core/cirq/linalg/transformations.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ def targeted_conjugate_about(
249249
tensor: np.ndarray,
250250
target: np.ndarray,
251251
indices: Sequence[int],
252-
conj_indices: Sequence[int] = None,
252+
conj_indices: Optional[Sequence[int]] = None,
253253
buffer: Optional[np.ndarray] = None,
254254
out: Optional[np.ndarray] = None,
255255
) -> np.ndarray:

Diff for: cirq-core/cirq/ops/clifford_gate.py

-6
Original file line numberDiff line numberDiff line change
@@ -75,12 +75,6 @@ def _to_clifford_tableau(
7575
return clifford_tableau
7676

7777

78-
def _pretend_initialized() -> 'SingleQubitCliffordGate':
79-
# HACK: This is a workaround to fool mypy and pylint into correctly handling
80-
# class fields that can't be initialized until after the class is defined.
81-
pass
82-
83-
8478
def _validate_map_input(
8579
required_transform_count: int,
8680
pauli_map_to: Optional[Dict[Pauli, Tuple[Pauli, bool]]],

Diff for: cirq-core/cirq/ops/common_gates.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ def _trace_distance_bound_(self) -> Optional[float]:
187187

188188
def controlled(
189189
self,
190-
num_controls: int = None,
190+
num_controls: Optional[int] = None,
191191
control_values: Optional[
192192
Union[cv.AbstractControlValues, Sequence[Union[int, Collection[int]]]]
193193
] = None,
@@ -667,7 +667,7 @@ def with_canonical_global_phase(self) -> 'ZPowGate':
667667

668668
def controlled(
669669
self,
670-
num_controls: int = None,
670+
num_controls: Optional[int] = None,
671671
control_values: Optional[
672672
Union[cv.AbstractControlValues, Sequence[Union[int, Collection[int]]]]
673673
] = None,
@@ -1122,7 +1122,7 @@ def _phase_by_(self, phase_turns, qubit_index):
11221122

11231123
def controlled(
11241124
self,
1125-
num_controls: int = None,
1125+
num_controls: Optional[int] = None,
11261126
control_values: Optional[
11271127
Union[cv.AbstractControlValues, Sequence[Union[int, Collection[int]]]]
11281128
] = None,
@@ -1328,7 +1328,7 @@ def _pauli_expansion_(self) -> value.LinearDict[str]:
13281328

13291329
def controlled(
13301330
self,
1331-
num_controls: int = None,
1331+
num_controls: Optional[int] = None,
13321332
control_values: Optional[
13331333
Union[cv.AbstractControlValues, Sequence[Union[int, Collection[int]]]]
13341334
] = None,

0 commit comments

Comments
 (0)