Skip to content

Commit 084e273

Browse files
authored
Use f-strings instead of percent operator or str.format() (#6198)
Convert all `%` and `str.format()` expressions or disable pylint check where `str.format()` is more readable. Partially fixes #6171
1 parent b72a532 commit 084e273

File tree

70 files changed

+279
-546
lines changed

Some content is hidden

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

70 files changed

+279
-546
lines changed

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

+3-6
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
# TODO(#6171): enable the check and fix pylint errors
16-
# pylint: disable=consider-using-f-string
17-
1815
import itertools
1916

2017
import pytest
@@ -35,13 +32,13 @@ def _assert_same_diagram(actual: str, expected: str):
3532
"Diagram differs from the desired diagram.\n"
3633
'\n'
3734
'Actual diagram:\n'
38-
'{}\n'
35+
f'{actual}\n'
3936
'\n'
4037
'Desired diagram:\n'
41-
'{}\n'
38+
f'{expected}\n'
4239
'\n'
4340
'Highlighted differences:\n'
44-
'{}\n'.format(actual, expected, cirq.testing.highlight_text_differences(actual, expected))
41+
f'{cirq.testing.highlight_text_differences(actual, expected)}\n'
4542
)
4643

4744

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

+1-6
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
# TODO(#6171): enable the check and fix pylint errors
16-
# pylint: disable=consider-using-f-string
17-
1815
"""A structure for encapsulating entire circuits in an operation.
1916
2017
A CircuitOperation is an Operation object that wraps a FrozenCircuit. When
@@ -463,9 +460,7 @@ def __str__(self):
463460
# TODO: support out-of-line subcircuit definition in string format.
464461
msg_lines = str(self.circuit).split('\n')
465462
msg_width = max([len(line) for line in msg_lines])
466-
circuit_msg = '\n'.join(
467-
'[ {line:<{width}} ]'.format(line=line, width=msg_width) for line in msg_lines
468-
)
463+
circuit_msg = '\n'.join(f'[ {line:<{msg_width}} ]' for line in msg_lines)
469464
args = []
470465

471466
def dict_str(d: Mapping) -> str:

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

+3-10
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
# TODO(#6171): enable the check and fix pylint errors
16-
# pylint: disable=consider-using-f-string
17-
1815
from unittest import mock
1916
import pytest
2017

@@ -49,17 +46,13 @@ def assert_has_rendering(actual: TextDiagramDrawer, desired: str, **kwargs) -> N
4946
"Diagram's rendering differs from the desired rendering.\n"
5047
'\n'
5148
'Actual rendering:\n'
52-
'{}\n'
49+
f'{actual_diagram}\n'
5350
'\n'
5451
'Desired rendering:\n'
55-
'{}\n'
52+
f'{desired_diagram}\n'
5653
'\n'
5754
'Highlighted differences:\n'
58-
'{}\n'.format(
59-
actual_diagram,
60-
desired_diagram,
61-
ct.highlight_text_differences(actual_diagram, desired_diagram),
62-
)
55+
f'{ct.highlight_text_differences(actual_diagram, desired_diagram)}\n'
6356
)
6457

6558

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

+1-4
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
# TODO(#6171): enable the check and fix pylint errors
16-
# pylint: disable=consider-using-f-string
17-
1815
import enum
1916
import itertools
2017
from typing import Dict, Sequence, Tuple, Union, TYPE_CHECKING
@@ -136,7 +133,7 @@ def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs') -> Tuple[s
136133
if self.subgraph == BipartiteGraphType.MATCHING:
137134
name = 'Matching'
138135
elif self.subgraph == BipartiteGraphType.COMPLETE:
139-
name = 'K_{{{0}, {0}}}'.format(self.part_size)
136+
name = f'K_{{{self.part_size}, {self.part_size}}}'
140137
# NB: self.subgraph not in BipartiteGraphType caught by self.permutation
141138
arrow = '↦' if args.use_unicode_characters else '->'
142139

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

+2-5
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
# TODO(#6171): enable the check and fix pylint errors
16-
# pylint: disable=consider-using-f-string
17-
1815
from typing import Union, TYPE_CHECKING
1916

2017
import abc
@@ -39,8 +36,8 @@ def validate_operation(self, operation: 'cirq.Operation') -> None:
3936
isinstance(operation, ops.GateOperation) and isinstance(operation.gate, self.gate_types)
4037
):
4138
raise ValueError(
42-
'not (isinstance({0!r}, {1!r}) and '
43-
'ininstance({0!r}.gate, {2!r})'.format(operation, ops.Operation, self.gate_types)
39+
f'not (isinstance({operation!r}, {ops.Operation!r}) and '
40+
f'ininstance({operation!r}.gate, {self.gate_types!r})'
4441
)
4542

4643

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

+3-5
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
# TODO(#6171): enable the check and fix pylint errors
16-
# pylint: disable=consider-using-f-string
17-
1815
import functools
1916
import itertools
2017
import math
@@ -350,8 +347,9 @@ def permutation(self) -> Dict[int, int]:
350347
return {i: j for i, j in enumerate(reversed(range(sum(self.part_lens))))}
351348

352349
def __repr__(self) -> str:
353-
return 'cirq.contrib.acquaintance.SwapNetworkGate({!r}, {!r})'.format(
354-
self.part_lens, self.acquaintance_size
350+
return (
351+
'cirq.contrib.acquaintance.SwapNetworkGate('
352+
f'{self.part_lens!r}, {self.acquaintance_size!r})'
355353
)
356354

357355
def _value_equality_values_(self):

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

+3-8
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
# TODO(#6171): enable the check and fix pylint errors
16-
# pylint: disable=consider-using-f-string
17-
1815
from typing import cast, Sequence, TYPE_CHECKING
1916

2017
from cirq import devices, ops, protocols
@@ -32,13 +29,11 @@ def assert_permutation_decomposition_equivalence(gate: PermutationGate, n_qubits
3229
update_mapping(mapping, operations)
3330
expected_mapping = {qubits[j]: i for i, j in gate.permutation().items()}
3431
assert mapping == expected_mapping, (
35-
"{!r}.permutation({}) doesn't match decomposition.\n"
32+
f"{gate!r}.permutation({n_qubits}) doesn't match decomposition.\n"
3633
'\n'
3734
'Actual mapping:\n'
38-
'{}\n'
35+
f'{[mapping[q] for q in qubits]}\n'
3936
'\n'
4037
'Expected mapping:\n'
41-
'{}\n'.format(
42-
gate, n_qubits, [mapping[q] for q in qubits], [expected_mapping[q] for q in qubits]
43-
)
38+
f'{[expected_mapping[q] for q in qubits]}\n'
4439
)

Diff for: cirq-core/cirq/contrib/paulistring/recombine.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
# TODO(#6171): enable the check and fix pylint errors
16-
# pylint: disable=consider-using-f-string
17-
1815
from typing import Any, Callable, Iterable, Sequence, Tuple, Union, cast, List
1916

2017
from cirq import circuits, ops, protocols
@@ -86,10 +83,9 @@ def move_pauli_strings_into_circuit(
8683
# Pick the Pauli string that can be moved furthest through
8784
# the Clifford circuit
8885
for best_string_op, best_index, best_node in placements:
89-
assert (
90-
best_index <= last_index
91-
), "Unexpected insertion index order, {} >= {}, len: {}".format(
92-
best_index, last_index, len(output_ops)
86+
assert best_index <= last_index, (
87+
"Unexpected insertion index order, "
88+
f"{best_index} >= {last_index}, len: {len(output_ops)}"
9389
)
9490

9591
last_index = best_index

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

+15-23
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
# TODO(#6171): enable the check and fix pylint errors
16-
# pylint: disable=consider-using-f-string
17-
1815
import functools
1916
import operator
2017
from typing import Any, Callable, cast, Dict, Iterable, List, Optional, Union, TYPE_CHECKING
@@ -86,16 +83,15 @@ def __init__(
8683
def _validate_args(self, args: List[List[ops.Qid]], lineno: int):
8784
if len(args) != self.num_args:
8885
raise QasmException(
89-
"{} only takes {} arg(s) (qubits and/or registers), "
90-
"got: {}, at line {}".format(self.qasm_gate, self.num_args, len(args), lineno)
86+
f"{self.qasm_gate} only takes {self.num_args} arg(s) (qubits and/or registers), "
87+
f"got: {len(args)}, at line {lineno}"
9188
)
9289

9390
def _validate_params(self, params: List[float], lineno: int):
9491
if len(params) != self.num_params:
9592
raise QasmException(
96-
"{} takes {} parameter(s), got: {}, at line {}".format(
97-
self.qasm_gate, self.num_params, len(params), lineno
98-
)
93+
f"{self.qasm_gate} takes {self.num_params} parameter(s), "
94+
f"got: {len(params)}, at line {lineno}"
9995
)
10096

10197
def on(
@@ -291,8 +287,7 @@ def p_format(self, p):
291287
"""format : FORMAT_SPEC"""
292288
if p[1] != "2.0":
293289
raise QasmException(
294-
"Unsupported OpenQASM version: {}, "
295-
"only 2.0 is supported currently by Cirq".format(p[1])
290+
f"Unsupported OpenQASM version: {p[1]}, only 2.0 is supported currently by Cirq"
296291
)
297292

298293
# circuit : new_reg circuit
@@ -349,11 +344,8 @@ def _resolve_gate_operation(
349344
):
350345
gate_set = self.basic_gates if not self.qelibinc else self.all_gates
351346
if gate not in gate_set.keys():
352-
msg = 'Unknown gate "{}" at line {}{}'.format(
353-
gate,
354-
p.lineno(1),
355-
", did you forget to include qelib1.inc?" if not self.qelibinc else "",
356-
)
347+
tip = ", did you forget to include qelib1.inc?" if not self.qelibinc else ""
348+
msg = f'Unknown gate "{gate}" at line {p.lineno(1)}{tip}'
357349
raise QasmException(msg)
358350
p[0] = gate_set[gate].on(args=args, params=params, lineno=p.lineno(1))
359351

@@ -464,9 +456,9 @@ def p_quantum_arg_bit(self, p):
464456
size = self.qregs[reg]
465457
if idx >= size:
466458
raise QasmException(
467-
'Out of bounds qubit index {} '
468-
'on register {} of size {} '
469-
'at line {}'.format(idx, reg, size, p.lineno(1))
459+
f'Out of bounds qubit index {idx} '
460+
f'on register {reg} of size {size} '
461+
f'at line {p.lineno(1)}'
470462
)
471463
if arg_name not in self.qubits.keys():
472464
self.qubits[arg_name] = NamedQubit(arg_name)
@@ -483,9 +475,9 @@ def p_classical_arg_bit(self, p):
483475
size = self.cregs[reg]
484476
if idx >= size:
485477
raise QasmException(
486-
'Out of bounds bit index {} '
487-
'on classical register {} of size {} '
488-
'at line {}'.format(idx, reg, size, p.lineno(1))
478+
f'Out of bounds bit index {idx} '
479+
f'on classical register {reg} of size {size} '
480+
f'at line {p.lineno(1)}'
489481
)
490482
p[0] = [arg_name]
491483

@@ -499,8 +491,8 @@ def p_measurement(self, p):
499491

500492
if len(qreg) != len(creg):
501493
raise QasmException(
502-
'mismatched register sizes {} -> {} for measurement '
503-
'at line {}'.format(len(qreg), len(creg), p.lineno(1))
494+
f'mismatched register sizes {len(qreg)} -> {len(creg)} for measurement '
495+
f'at line {p.lineno(1)}'
504496
)
505497

506498
p[0] = [

0 commit comments

Comments
 (0)