Skip to content

Commit 3e25689

Browse files
committed
Switch to unquoted type annotations files part 5/5
1 parent 4cdc08c commit 3e25689

File tree

10 files changed

+108
-106
lines changed

10 files changed

+108
-106
lines changed

cirq-core/cirq/contrib/routing/utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from __future__ import annotations
16+
1517
import operator
1618
import re
1719
from typing import Callable, Iterable, List, TYPE_CHECKING
@@ -86,7 +88,7 @@ def is_valid_routing(
8688
raise
8789

8890

89-
def get_circuit_connectivity(circuit: 'cirq.Circuit') -> nx.Graph:
91+
def get_circuit_connectivity(circuit: cirq.Circuit) -> nx.Graph:
9092
"""Return a graph of all 2q interactions in a circuit.
9193
9294
Nodes are qubits and undirected edges correspond to any two-qubit

cirq-core/cirq/contrib/svg/svg.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
# pylint: disable=wrong-or-nonexistent-copyright-notice
2+
3+
from __future__ import annotations
4+
25
from typing import cast, Dict, List, Tuple, TYPE_CHECKING
36

47
import matplotlib.font_manager
@@ -59,7 +62,7 @@ def _text(x: float, y: float, text: str, fontsize: int = 14):
5962

6063

6164
def _fit_horizontal(
62-
tdd: 'cirq.TextDiagramDrawer', ref_boxwidth: float, col_padding: float
65+
tdd: cirq.TextDiagramDrawer, ref_boxwidth: float, col_padding: float
6366
) -> Tuple[List[float], List[float]]:
6467
"""Figure out the horizontal spacing of columns to fit everything in.
6568
@@ -89,7 +92,7 @@ def _fit_horizontal(
8992

9093

9194
def _fit_vertical(
92-
tdd: 'cirq.TextDiagramDrawer', ref_boxheight: float, row_padding: float
95+
tdd: cirq.TextDiagramDrawer, ref_boxheight: float, row_padding: float
9396
) -> Tuple[List[float], List[float], Dict[float, int]]:
9497
"""Return data structures used to turn tdd vertical coordinates into
9598
well-spaced SVG coordinates.
@@ -164,7 +167,7 @@ def _debug_spacing(col_starts, row_starts): # pragma: no cover
164167

165168

166169
def tdd_to_svg(
167-
tdd: 'cirq.TextDiagramDrawer',
170+
tdd: cirq.TextDiagramDrawer,
168171
ref_boxwidth: float = 40,
169172
ref_boxheight: float = 40,
170173
col_padding: float = 20,
@@ -246,7 +249,7 @@ def tdd_to_svg(
246249
return t
247250

248251

249-
def _validate_circuit(circuit: 'cirq.Circuit'):
252+
def _validate_circuit(circuit: cirq.Circuit):
250253
if len(circuit) == 0:
251254
raise ValueError("Can't draw SVG diagram for empty circuits")
252255

@@ -260,14 +263,14 @@ class SVGCircuit:
260263
which will cause the circuit to be displayed as an SVG image.
261264
"""
262265

263-
def __init__(self, circuit: 'cirq.Circuit'):
266+
def __init__(self, circuit: cirq.Circuit):
264267
self.circuit = circuit
265268

266269
def _repr_svg_(self) -> str:
267270
return circuit_to_svg(self.circuit)
268271

269272

270-
def circuit_to_svg(circuit: 'cirq.Circuit') -> str:
273+
def circuit_to_svg(circuit: cirq.Circuit) -> str:
271274
"""Render a circuit as SVG."""
272275
_validate_circuit(circuit)
273276
tdd = circuit.to_text_diagram_drawer(transpose=False)

cirq-core/cirq/devices/device.py

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

15+
from __future__ import annotations
16+
1517
import abc
1618
from typing import FrozenSet, Iterable, Optional, TYPE_CHECKING
1719

@@ -57,15 +59,15 @@ class Device(metaclass=abc.ABCMeta):
5759
"""
5860

5961
@property
60-
def metadata(self) -> Optional['DeviceMetadata']:
62+
def metadata(self) -> Optional[DeviceMetadata]:
6163
"""Returns the associated Metadata with the device if applicable.
6264
6365
Returns:
6466
`cirq.DeviceMetadata` if specified by the device otherwise None.
6567
"""
6668
return None
6769

68-
def validate_operation(self, operation: 'cirq.Operation') -> None:
70+
def validate_operation(self, operation: cirq.Operation) -> None:
6971
"""Raises an exception if an operation is not valid.
7072
7173
Args:
@@ -75,7 +77,7 @@ def validate_operation(self, operation: 'cirq.Operation') -> None:
7577
ValueError: The operation isn't valid for this device.
7678
"""
7779

78-
def validate_circuit(self, circuit: 'cirq.AbstractCircuit') -> None:
80+
def validate_circuit(self, circuit: cirq.AbstractCircuit) -> None:
7981
"""Raises an exception if a circuit is not valid.
8082
8183
Args:
@@ -87,7 +89,7 @@ def validate_circuit(self, circuit: 'cirq.AbstractCircuit') -> None:
8789
for moment in circuit:
8890
self.validate_moment(moment)
8991

90-
def validate_moment(self, moment: 'cirq.Moment') -> None:
92+
def validate_moment(self, moment: cirq.Moment) -> None:
9193
"""Raises an exception if a moment is not valid.
9294
9395
Args:
@@ -104,7 +106,7 @@ def validate_moment(self, moment: 'cirq.Moment') -> None:
104106
class DeviceMetadata:
105107
"""Parent type for all device specific metadata classes."""
106108

107-
def __init__(self, qubits: Iterable['cirq.Qid'], nx_graph: 'nx.Graph'):
109+
def __init__(self, qubits: Iterable[cirq.Qid], nx_graph: nx.Graph):
108110
"""Construct a DeviceMetadata object.
109111
110112
Args:
@@ -114,11 +116,11 @@ def __init__(self, qubits: Iterable['cirq.Qid'], nx_graph: 'nx.Graph'):
114116
directional coupling, undirected edges indicate bi-directional
115117
coupling.
116118
"""
117-
self._qubits_set: FrozenSet['cirq.Qid'] = frozenset(qubits)
119+
self._qubits_set: FrozenSet[cirq.Qid] = frozenset(qubits)
118120
self._nx_graph = nx_graph
119121

120122
@property
121-
def qubit_set(self) -> FrozenSet['cirq.Qid']:
123+
def qubit_set(self) -> FrozenSet[cirq.Qid]:
122124
"""Returns the set of qubits on the device.
123125
124126
Returns:
@@ -127,7 +129,7 @@ def qubit_set(self) -> FrozenSet['cirq.Qid']:
127129
return self._qubits_set
128130

129131
@property
130-
def nx_graph(self) -> 'nx.Graph':
132+
def nx_graph(self) -> nx.Graph:
131133
"""Returns a nx.Graph where nodes are qubits and edges are couple-able qubits.
132134
133135
Returns:
@@ -150,6 +152,6 @@ def _json_dict_(self):
150152
return {'qubits': qubits_payload, 'nx_graph': graph_payload}
151153

152154
@classmethod
153-
def _from_json_dict_(cls, qubits: Iterable['cirq.Qid'], nx_graph: 'nx.Graph', **kwargs):
155+
def _from_json_dict_(cls, qubits: Iterable[cirq.Qid], nx_graph: nx.Graph, **kwargs):
154156
graph_obj = nx.readwrite.json_graph.node_link_graph(nx_graph)
155157
return cls(qubits, graph_obj)

cirq-core/cirq/devices/grid_device_metadata.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,11 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
1415
"""Metadata subtype for 2D Homogenous devices."""
1516

17+
from __future__ import annotations
18+
1619
from typing import cast, FrozenSet, Iterable, Mapping, Optional, Tuple, TYPE_CHECKING
1720

1821
import networkx as nx
@@ -30,11 +33,11 @@ class GridDeviceMetadata(device.DeviceMetadata):
3033

3134
def __init__(
3235
self,
33-
qubit_pairs: Iterable[Tuple['cirq.GridQubit', 'cirq.GridQubit']],
34-
gateset: 'cirq.Gateset',
35-
gate_durations: Optional[Mapping['cirq.GateFamily', 'cirq.Duration']] = None,
36-
all_qubits: Optional[Iterable['cirq.GridQubit']] = None,
37-
compilation_target_gatesets: Iterable['cirq.CompilationTargetGateset'] = (),
36+
qubit_pairs: Iterable[Tuple[cirq.GridQubit, cirq.GridQubit]],
37+
gateset: cirq.Gateset,
38+
gate_durations: Optional[Mapping[cirq.GateFamily, cirq.Duration]] = None,
39+
all_qubits: Optional[Iterable[cirq.GridQubit]] = None,
40+
compilation_target_gatesets: Iterable[cirq.CompilationTargetGateset] = (),
3841
):
3942
"""Create a GridDeviceMetadata object.
4043
@@ -115,7 +118,7 @@ def __init__(
115118
self._gate_durations = gate_durations
116119

117120
@property
118-
def qubit_set(self) -> FrozenSet['cirq.GridQubit']:
121+
def qubit_set(self) -> FrozenSet[cirq.GridQubit]:
119122
"""Returns the set of grid qubits on the device.
120123
121124
Returns:
@@ -124,7 +127,7 @@ def qubit_set(self) -> FrozenSet['cirq.GridQubit']:
124127
return cast(FrozenSet['cirq.GridQubit'], super().qubit_set)
125128

126129
@property
127-
def qubit_pairs(self) -> FrozenSet[FrozenSet['cirq.GridQubit']]:
130+
def qubit_pairs(self) -> FrozenSet[FrozenSet[cirq.GridQubit]]:
128131
"""Returns the set of all couple-able qubits on the device.
129132
130133
Each element in the outer frozenset is a 2-element frozenset representing a bidirectional
@@ -133,22 +136,22 @@ def qubit_pairs(self) -> FrozenSet[FrozenSet['cirq.GridQubit']]:
133136
return self._qubit_pairs
134137

135138
@property
136-
def isolated_qubits(self) -> FrozenSet['cirq.GridQubit']:
139+
def isolated_qubits(self) -> FrozenSet[cirq.GridQubit]:
137140
"""Returns the set of all isolated qubits on the device (if applicable)."""
138141
return self._isolated_qubits
139142

140143
@property
141-
def gateset(self) -> 'cirq.Gateset':
144+
def gateset(self) -> cirq.Gateset:
142145
"""Returns the `cirq.Gateset` of supported gates on this device."""
143146
return self._gateset
144147

145148
@property
146-
def compilation_target_gatesets(self) -> Tuple['cirq.CompilationTargetGateset', ...]:
149+
def compilation_target_gatesets(self) -> Tuple[cirq.CompilationTargetGateset, ...]:
147150
"""Returns a sequence of valid `cirq.CompilationTargetGateset`s for this device."""
148151
return self._compilation_target_gatesets
149152

150153
@property
151-
def gate_durations(self) -> Optional[Mapping['cirq.GateFamily', 'cirq.Duration']]:
154+
def gate_durations(self) -> Optional[Mapping[cirq.GateFamily, cirq.Duration]]:
152155
"""Get a dictionary mapping from gate family to duration for gates.
153156
154157
To look up the duration of a specific gate instance / gate type / operation which is part of

cirq-core/cirq/devices/grid_qubit.py

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

15+
from __future__ import annotations
16+
1517
import abc
1618
import functools
1719
import weakref
@@ -104,17 +106,17 @@ def col(self) -> int:
104106
def dimension(self) -> int:
105107
return self._dimension
106108

107-
def with_dimension(self, dimension: int) -> 'GridQid':
109+
def with_dimension(self, dimension: int) -> GridQid:
108110
return GridQid(self._row, self._col, dimension=dimension)
109111

110-
def is_adjacent(self, other: 'cirq.Qid') -> bool:
112+
def is_adjacent(self, other: cirq.Qid) -> bool:
111113
"""Determines if two qubits are adjacent qubits."""
112114
return (
113115
isinstance(other, GridQubit)
114116
and abs(self._row - other._row) + abs(self._col - other._col) == 1
115117
)
116118

117-
def neighbors(self, qids: Optional[Iterable[ops.Qid]] = None) -> Set['_BaseGridQid']:
119+
def neighbors(self, qids: Optional[Iterable[ops.Qid]] = None) -> Set[_BaseGridQid]:
118120
"""Returns qubits that are potential neighbors to this GridQid
119121
120122
Args:
@@ -204,7 +206,7 @@ class GridQid(_BaseGridQid):
204206
# Holds weak references so instances can still be garbage collected.
205207
_cache = weakref.WeakValueDictionary[Tuple[int, int, int], 'cirq.GridQid']()
206208

207-
def __new__(cls, row: int, col: int, *, dimension: int) -> 'cirq.GridQid':
209+
def __new__(cls, row: int, col: int, *, dimension: int) -> cirq.GridQid:
208210
"""Creates a grid qid at the given row, col coordinate
209211
210212
Args:
@@ -234,11 +236,11 @@ def __getnewargs_ex__(self):
234236
def __getstate__(self) -> Dict[str, Any]:
235237
return {}
236238

237-
def _with_row_col(self, row: int, col: int) -> 'GridQid':
239+
def _with_row_col(self, row: int, col: int) -> GridQid:
238240
return GridQid(row, col, dimension=self._dimension)
239241

240242
@staticmethod
241-
def square(diameter: int, top: int = 0, left: int = 0, *, dimension: int) -> List['GridQid']:
243+
def square(diameter: int, top: int = 0, left: int = 0, *, dimension: int) -> List[GridQid]:
242244
"""Returns a square of GridQid.
243245
244246
Args:
@@ -254,9 +256,7 @@ def square(diameter: int, top: int = 0, left: int = 0, *, dimension: int) -> Lis
254256
return GridQid.rect(diameter, diameter, top=top, left=left, dimension=dimension)
255257

256258
@staticmethod
257-
def rect(
258-
rows: int, cols: int, top: int = 0, left: int = 0, *, dimension: int
259-
) -> List['GridQid']:
259+
def rect(rows: int, cols: int, top: int = 0, left: int = 0, *, dimension: int) -> List[GridQid]:
260260
"""Returns a rectangle of GridQid.
261261
262262
Args:
@@ -277,7 +277,7 @@ def rect(
277277
]
278278

279279
@staticmethod
280-
def from_diagram(diagram: str, dimension: int) -> List['GridQid']:
280+
def from_diagram(diagram: str, dimension: int) -> List[GridQid]:
281281
"""Parse ASCII art device layout into a device.
282282
283283
As an example, the below diagram will create a list of GridQid in a
@@ -337,9 +337,7 @@ def __repr__(self) -> str:
337337
def __str__(self) -> str:
338338
return f"q({self._row}, {self._col}) (d={self._dimension})"
339339

340-
def _circuit_diagram_info_(
341-
self, args: 'cirq.CircuitDiagramInfoArgs'
342-
) -> 'cirq.CircuitDiagramInfo':
340+
def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> cirq.CircuitDiagramInfo:
343341
return protocols.CircuitDiagramInfo(
344342
wire_symbols=(f"({self._row}, {self._col}) (d={self._dimension})",)
345343
)
@@ -371,7 +369,7 @@ class GridQubit(_BaseGridQid):
371369
# Holds weak references so instances can still be garbage collected.
372370
_cache = weakref.WeakValueDictionary[Tuple[int, int], 'cirq.GridQubit']()
373371

374-
def __new__(cls, row: int, col: int) -> 'cirq.GridQubit':
372+
def __new__(cls, row: int, col: int) -> cirq.GridQubit:
375373
"""Creates a grid qubit at the given row, col coordinate
376374
377375
Args:
@@ -396,11 +394,11 @@ def __getnewargs__(self):
396394
def __getstate__(self) -> Dict[str, Any]:
397395
return {}
398396

399-
def _with_row_col(self, row: int, col: int) -> 'GridQubit':
397+
def _with_row_col(self, row: int, col: int) -> GridQubit:
400398
return GridQubit(row, col)
401399

402400
@staticmethod
403-
def square(diameter: int, top: int = 0, left: int = 0) -> List['GridQubit']:
401+
def square(diameter: int, top: int = 0, left: int = 0) -> List[GridQubit]:
404402
"""Returns a square of GridQubits.
405403
406404
Args:
@@ -414,7 +412,7 @@ def square(diameter: int, top: int = 0, left: int = 0) -> List['GridQubit']:
414412
return GridQubit.rect(diameter, diameter, top=top, left=left)
415413

416414
@staticmethod
417-
def rect(rows: int, cols: int, top: int = 0, left: int = 0) -> List['GridQubit']:
415+
def rect(rows: int, cols: int, top: int = 0, left: int = 0) -> List[GridQubit]:
418416
"""Returns a rectangle of GridQubits.
419417
420418
Args:
@@ -433,7 +431,7 @@ def rect(rows: int, cols: int, top: int = 0, left: int = 0) -> List['GridQubit']
433431
]
434432

435433
@staticmethod
436-
def from_diagram(diagram: str) -> List['GridQubit']:
434+
def from_diagram(diagram: str) -> List[GridQubit]:
437435
"""Parse ASCII art into device layout info.
438436
439437
As an example, the below diagram will create a list of
@@ -490,9 +488,7 @@ def __repr__(self) -> str:
490488
def __str__(self) -> str:
491489
return f"q({self._row}, {self._col})"
492490

493-
def _circuit_diagram_info_(
494-
self, args: 'cirq.CircuitDiagramInfoArgs'
495-
) -> 'cirq.CircuitDiagramInfo':
491+
def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs) -> cirq.CircuitDiagramInfo:
496492
return protocols.CircuitDiagramInfo(wire_symbols=(f"({self._row}, {self._col})",))
497493

498494
def _json_dict_(self) -> Dict[str, Any]:

cirq-core/cirq/devices/grid_qubit_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def test_grid_qid_pickled_hash():
5858
_test_qid_pickled_hash(q, q_bad)
5959

6060

61-
def _test_qid_pickled_hash(q: 'cirq.Qid', q_bad: 'cirq.Qid') -> None:
61+
def _test_qid_pickled_hash(q: cirq.Qid, q_bad: cirq.Qid) -> None:
6262
"""Test that hashes are not pickled with Qid instances."""
6363
assert q_bad is not q
6464
_ = hash(q_bad) # compute hash to ensure it is cached.

0 commit comments

Comments
 (0)