Skip to content

Commit

Permalink
Use f-strings instead of percent operator or str.format() (#6198)
Browse files Browse the repository at this point in the history
Convert all `%` and `str.format()` expressions or disable pylint
check where `str.format()` is more readable.

Partially fixes #6171
  • Loading branch information
pavoljuhas committed Jul 17, 2023
1 parent b72a532 commit 084e273
Show file tree
Hide file tree
Showing 70 changed files with 279 additions and 546 deletions.
9 changes: 3 additions & 6 deletions cirq-core/cirq/circuits/_block_diagram_drawer_test.py
Expand Up @@ -12,9 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# TODO(#6171): enable the check and fix pylint errors
# pylint: disable=consider-using-f-string

import itertools

import pytest
Expand All @@ -35,13 +32,13 @@ def _assert_same_diagram(actual: str, expected: str):
"Diagram differs from the desired diagram.\n"
'\n'
'Actual diagram:\n'
'{}\n'
f'{actual}\n'
'\n'
'Desired diagram:\n'
'{}\n'
f'{expected}\n'
'\n'
'Highlighted differences:\n'
'{}\n'.format(actual, expected, cirq.testing.highlight_text_differences(actual, expected))
f'{cirq.testing.highlight_text_differences(actual, expected)}\n'
)


Expand Down
7 changes: 1 addition & 6 deletions cirq-core/cirq/circuits/circuit_operation.py
Expand Up @@ -12,9 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# TODO(#6171): enable the check and fix pylint errors
# pylint: disable=consider-using-f-string

"""A structure for encapsulating entire circuits in an operation.
A CircuitOperation is an Operation object that wraps a FrozenCircuit. When
Expand Down Expand Up @@ -463,9 +460,7 @@ def __str__(self):
# TODO: support out-of-line subcircuit definition in string format.
msg_lines = str(self.circuit).split('\n')
msg_width = max([len(line) for line in msg_lines])
circuit_msg = '\n'.join(
'[ {line:<{width}} ]'.format(line=line, width=msg_width) for line in msg_lines
)
circuit_msg = '\n'.join(f'[ {line:<{msg_width}} ]' for line in msg_lines)
args = []

def dict_str(d: Mapping) -> str:
Expand Down
13 changes: 3 additions & 10 deletions cirq-core/cirq/circuits/text_diagram_drawer_test.py
Expand Up @@ -12,9 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# TODO(#6171): enable the check and fix pylint errors
# pylint: disable=consider-using-f-string

from unittest import mock
import pytest

Expand Down Expand Up @@ -49,17 +46,13 @@ def assert_has_rendering(actual: TextDiagramDrawer, desired: str, **kwargs) -> N
"Diagram's rendering differs from the desired rendering.\n"
'\n'
'Actual rendering:\n'
'{}\n'
f'{actual_diagram}\n'
'\n'
'Desired rendering:\n'
'{}\n'
f'{desired_diagram}\n'
'\n'
'Highlighted differences:\n'
'{}\n'.format(
actual_diagram,
desired_diagram,
ct.highlight_text_differences(actual_diagram, desired_diagram),
)
f'{ct.highlight_text_differences(actual_diagram, desired_diagram)}\n'
)


Expand Down
5 changes: 1 addition & 4 deletions cirq-core/cirq/contrib/acquaintance/bipartite.py
Expand Up @@ -12,9 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# TODO(#6171): enable the check and fix pylint errors
# pylint: disable=consider-using-f-string

import enum
import itertools
from typing import Dict, Sequence, Tuple, Union, TYPE_CHECKING
Expand Down Expand Up @@ -136,7 +133,7 @@ def _circuit_diagram_info_(self, args: 'cirq.CircuitDiagramInfoArgs') -> Tuple[s
if self.subgraph == BipartiteGraphType.MATCHING:
name = 'Matching'
elif self.subgraph == BipartiteGraphType.COMPLETE:
name = 'K_{{{0}, {0}}}'.format(self.part_size)
name = f'K_{{{self.part_size}, {self.part_size}}}'
# NB: self.subgraph not in BipartiteGraphType caught by self.permutation
arrow = '↦' if args.use_unicode_characters else '->'

Expand Down
7 changes: 2 additions & 5 deletions cirq-core/cirq/contrib/acquaintance/devices.py
Expand Up @@ -12,9 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# TODO(#6171): enable the check and fix pylint errors
# pylint: disable=consider-using-f-string

from typing import Union, TYPE_CHECKING

import abc
Expand All @@ -39,8 +36,8 @@ def validate_operation(self, operation: 'cirq.Operation') -> None:
isinstance(operation, ops.GateOperation) and isinstance(operation.gate, self.gate_types)
):
raise ValueError(
'not (isinstance({0!r}, {1!r}) and '
'ininstance({0!r}.gate, {2!r})'.format(operation, ops.Operation, self.gate_types)
f'not (isinstance({operation!r}, {ops.Operation!r}) and '
f'ininstance({operation!r}.gate, {self.gate_types!r})'
)


Expand Down
8 changes: 3 additions & 5 deletions cirq-core/cirq/contrib/acquaintance/gates.py
Expand Up @@ -12,9 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# TODO(#6171): enable the check and fix pylint errors
# pylint: disable=consider-using-f-string

import functools
import itertools
import math
Expand Down Expand Up @@ -350,8 +347,9 @@ def permutation(self) -> Dict[int, int]:
return {i: j for i, j in enumerate(reversed(range(sum(self.part_lens))))}

def __repr__(self) -> str:
return 'cirq.contrib.acquaintance.SwapNetworkGate({!r}, {!r})'.format(
self.part_lens, self.acquaintance_size
return (
'cirq.contrib.acquaintance.SwapNetworkGate('
f'{self.part_lens!r}, {self.acquaintance_size!r})'
)

def _value_equality_values_(self):
Expand Down
11 changes: 3 additions & 8 deletions cirq-core/cirq/contrib/acquaintance/testing.py
Expand Up @@ -12,9 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# TODO(#6171): enable the check and fix pylint errors
# pylint: disable=consider-using-f-string

from typing import cast, Sequence, TYPE_CHECKING

from cirq import devices, ops, protocols
Expand All @@ -32,13 +29,11 @@ def assert_permutation_decomposition_equivalence(gate: PermutationGate, n_qubits
update_mapping(mapping, operations)
expected_mapping = {qubits[j]: i for i, j in gate.permutation().items()}
assert mapping == expected_mapping, (
"{!r}.permutation({}) doesn't match decomposition.\n"
f"{gate!r}.permutation({n_qubits}) doesn't match decomposition.\n"
'\n'
'Actual mapping:\n'
'{}\n'
f'{[mapping[q] for q in qubits]}\n'
'\n'
'Expected mapping:\n'
'{}\n'.format(
gate, n_qubits, [mapping[q] for q in qubits], [expected_mapping[q] for q in qubits]
)
f'{[expected_mapping[q] for q in qubits]}\n'
)
10 changes: 3 additions & 7 deletions cirq-core/cirq/contrib/paulistring/recombine.py
Expand Up @@ -12,9 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# TODO(#6171): enable the check and fix pylint errors
# pylint: disable=consider-using-f-string

from typing import Any, Callable, Iterable, Sequence, Tuple, Union, cast, List

from cirq import circuits, ops, protocols
Expand Down Expand Up @@ -86,10 +83,9 @@ def move_pauli_strings_into_circuit(
# Pick the Pauli string that can be moved furthest through
# the Clifford circuit
for best_string_op, best_index, best_node in placements:
assert (
best_index <= last_index
), "Unexpected insertion index order, {} >= {}, len: {}".format(
best_index, last_index, len(output_ops)
assert best_index <= last_index, (
"Unexpected insertion index order, "
f"{best_index} >= {last_index}, len: {len(output_ops)}"
)

last_index = best_index
Expand Down
38 changes: 15 additions & 23 deletions cirq-core/cirq/contrib/qasm_import/_parser.py
Expand Up @@ -12,9 +12,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.

# TODO(#6171): enable the check and fix pylint errors
# pylint: disable=consider-using-f-string

import functools
import operator
from typing import Any, Callable, cast, Dict, Iterable, List, Optional, Union, TYPE_CHECKING
Expand Down Expand Up @@ -86,16 +83,15 @@ def __init__(
def _validate_args(self, args: List[List[ops.Qid]], lineno: int):
if len(args) != self.num_args:
raise QasmException(
"{} only takes {} arg(s) (qubits and/or registers), "
"got: {}, at line {}".format(self.qasm_gate, self.num_args, len(args), lineno)
f"{self.qasm_gate} only takes {self.num_args} arg(s) (qubits and/or registers), "
f"got: {len(args)}, at line {lineno}"
)

def _validate_params(self, params: List[float], lineno: int):
if len(params) != self.num_params:
raise QasmException(
"{} takes {} parameter(s), got: {}, at line {}".format(
self.qasm_gate, self.num_params, len(params), lineno
)
f"{self.qasm_gate} takes {self.num_params} parameter(s), "
f"got: {len(params)}, at line {lineno}"
)

def on(
Expand Down Expand Up @@ -291,8 +287,7 @@ def p_format(self, p):
"""format : FORMAT_SPEC"""
if p[1] != "2.0":
raise QasmException(
"Unsupported OpenQASM version: {}, "
"only 2.0 is supported currently by Cirq".format(p[1])
f"Unsupported OpenQASM version: {p[1]}, only 2.0 is supported currently by Cirq"
)

# circuit : new_reg circuit
Expand Down Expand Up @@ -349,11 +344,8 @@ def _resolve_gate_operation(
):
gate_set = self.basic_gates if not self.qelibinc else self.all_gates
if gate not in gate_set.keys():
msg = 'Unknown gate "{}" at line {}{}'.format(
gate,
p.lineno(1),
", did you forget to include qelib1.inc?" if not self.qelibinc else "",
)
tip = ", did you forget to include qelib1.inc?" if not self.qelibinc else ""
msg = f'Unknown gate "{gate}" at line {p.lineno(1)}{tip}'
raise QasmException(msg)
p[0] = gate_set[gate].on(args=args, params=params, lineno=p.lineno(1))

Expand Down Expand Up @@ -464,9 +456,9 @@ def p_quantum_arg_bit(self, p):
size = self.qregs[reg]
if idx >= size:
raise QasmException(
'Out of bounds qubit index {} '
'on register {} of size {} '
'at line {}'.format(idx, reg, size, p.lineno(1))
f'Out of bounds qubit index {idx} '
f'on register {reg} of size {size} '
f'at line {p.lineno(1)}'
)
if arg_name not in self.qubits.keys():
self.qubits[arg_name] = NamedQubit(arg_name)
Expand All @@ -483,9 +475,9 @@ def p_classical_arg_bit(self, p):
size = self.cregs[reg]
if idx >= size:
raise QasmException(
'Out of bounds bit index {} '
'on classical register {} of size {} '
'at line {}'.format(idx, reg, size, p.lineno(1))
f'Out of bounds bit index {idx} '
f'on classical register {reg} of size {size} '
f'at line {p.lineno(1)}'
)
p[0] = [arg_name]

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

if len(qreg) != len(creg):
raise QasmException(
'mismatched register sizes {} -> {} for measurement '
'at line {}'.format(len(qreg), len(creg), p.lineno(1))
f'mismatched register sizes {len(qreg)} -> {len(creg)} for measurement '
f'at line {p.lineno(1)}'
)

p[0] = [
Expand Down

0 comments on commit 084e273

Please sign in to comment.