diff --git a/cirq-core/cirq/circuits/_block_diagram_drawer_test.py b/cirq-core/cirq/circuits/_block_diagram_drawer_test.py index f219adaaa6f..da84361331f 100644 --- a/cirq-core/cirq/circuits/_block_diagram_drawer_test.py +++ b/cirq-core/cirq/circuits/_block_diagram_drawer_test.py @@ -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 @@ -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' ) diff --git a/cirq-core/cirq/circuits/circuit_operation.py b/cirq-core/cirq/circuits/circuit_operation.py index 2bf932c9413..9f81a33714b 100644 --- a/cirq-core/cirq/circuits/circuit_operation.py +++ b/cirq-core/cirq/circuits/circuit_operation.py @@ -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 @@ -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: diff --git a/cirq-core/cirq/circuits/text_diagram_drawer_test.py b/cirq-core/cirq/circuits/text_diagram_drawer_test.py index 78f0318c418..c255e8b583a 100644 --- a/cirq-core/cirq/circuits/text_diagram_drawer_test.py +++ b/cirq-core/cirq/circuits/text_diagram_drawer_test.py @@ -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 @@ -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' ) diff --git a/cirq-core/cirq/contrib/acquaintance/bipartite.py b/cirq-core/cirq/contrib/acquaintance/bipartite.py index 8076039aa15..53a518976f3 100644 --- a/cirq-core/cirq/contrib/acquaintance/bipartite.py +++ b/cirq-core/cirq/contrib/acquaintance/bipartite.py @@ -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 @@ -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 '->' diff --git a/cirq-core/cirq/contrib/acquaintance/devices.py b/cirq-core/cirq/contrib/acquaintance/devices.py index 1cc03e21b50..f40dedb1dd9 100644 --- a/cirq-core/cirq/contrib/acquaintance/devices.py +++ b/cirq-core/cirq/contrib/acquaintance/devices.py @@ -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 @@ -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})' ) diff --git a/cirq-core/cirq/contrib/acquaintance/gates.py b/cirq-core/cirq/contrib/acquaintance/gates.py index 2cc80234aa9..065646dbd3e 100644 --- a/cirq-core/cirq/contrib/acquaintance/gates.py +++ b/cirq-core/cirq/contrib/acquaintance/gates.py @@ -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 @@ -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): diff --git a/cirq-core/cirq/contrib/acquaintance/testing.py b/cirq-core/cirq/contrib/acquaintance/testing.py index 21f9b2dd1f2..cc7f55abd81 100644 --- a/cirq-core/cirq/contrib/acquaintance/testing.py +++ b/cirq-core/cirq/contrib/acquaintance/testing.py @@ -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 @@ -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' ) diff --git a/cirq-core/cirq/contrib/paulistring/recombine.py b/cirq-core/cirq/contrib/paulistring/recombine.py index 03d9eb5d5f3..91fcb3eaf14 100644 --- a/cirq-core/cirq/contrib/paulistring/recombine.py +++ b/cirq-core/cirq/contrib/paulistring/recombine.py @@ -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 @@ -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 diff --git a/cirq-core/cirq/contrib/qasm_import/_parser.py b/cirq-core/cirq/contrib/qasm_import/_parser.py index 005a6327152..e7bcdae06db 100644 --- a/cirq-core/cirq/contrib/qasm_import/_parser.py +++ b/cirq-core/cirq/contrib/qasm_import/_parser.py @@ -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 @@ -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( @@ -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 @@ -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)) @@ -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) @@ -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] @@ -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] = [ diff --git a/cirq-core/cirq/contrib/qasm_import/_parser_test.py b/cirq-core/cirq/contrib/qasm_import/_parser_test.py index 1c596ddde27..4b0ca8e50f1 100644 --- a/cirq-core/cirq/contrib/qasm_import/_parser_test.py +++ b/cirq-core/cirq/contrib/qasm_import/_parser_test.py @@ -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 Callable import numpy as np @@ -493,14 +490,12 @@ def test_unknown_function(): @pytest.mark.parametrize('qasm_gate,cirq_gate', rotation_gates) def test_rotation_gates(qasm_gate: str, cirq_gate: Callable[[float], cirq.Gate]): - qasm = """OPENQASM 2.0; + qasm = f"""OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; - {0}(pi/2) q[0]; - {0}(pi) q; - """.format( - qasm_gate - ) + {qasm_gate}(pi/2) q[0]; + {qasm_gate}(pi) q; + """ parser = QasmParser() @@ -531,7 +526,7 @@ def test_rotation_gates_wrong_number_of_args(qasm_gate: str): parser = QasmParser() - with pytest.raises(QasmException, match=r".*{}.* takes 1.*got.*2.*line 5".format(qasm_gate)): + with pytest.raises(QasmException, match=f".*{qasm_gate}.* takes 1.*got.*2.*line 5"): parser.parse(qasm) @@ -545,7 +540,7 @@ def test_rotation_gates_zero_params_error(qasm_gate: str): parser = QasmParser() - with pytest.raises(QasmException, match=r".*{}.* takes 1.*got.*0.*line 4".format(qasm_gate)): + with pytest.raises(QasmException, match=f".*{qasm_gate}.* takes 1.*got.*0.*line 4"): parser.parse(qasm) @@ -871,9 +866,7 @@ def test_standard_gates_wrong_params_error(qasm_gate: str, num_params: int): parser = QasmParser() - with pytest.raises( - QasmException, match=r".*{}.* takes {}.*got.*5.*line 4".format(qasm_gate, num_params) - ): + with pytest.raises(QasmException, match=f".*{qasm_gate}.* takes {num_params}.*got.*5.*line 4"): parser.parse(qasm) if num_params == 0: @@ -887,9 +880,7 @@ def test_standard_gates_wrong_params_error(qasm_gate: str, num_params: int): parser = QasmParser() - with pytest.raises( - QasmException, match=r".*{}.* takes {}.*got.*0.*line 4".format(qasm_gate, num_params) - ): + with pytest.raises(QasmException, match=f".*{qasm_gate}.* takes {num_params}.*got.*0.*line 4"): parser.parse(qasm) @@ -905,17 +896,15 @@ def test_standard_gates_wrong_params_error(qasm_gate: str, num_params: int): @pytest.mark.parametrize('qasm_gate,cirq_gate', two_qubit_gates) def test_two_qubit_gates(qasm_gate: str, cirq_gate: cirq.testing.TwoQubitGate): - qasm = """ - OPENQASM 2.0; - include "qelib1.inc"; + qasm = f""" + OPENQASM 2.0; + include "qelib1.inc"; qreg q1[2]; qreg q2[2]; - {0} q1[0], q1[1]; - {0} q1, q2[0]; - {0} q2, q1; -""".format( - qasm_gate - ) + {qasm_gate} q1[0], q1[1]; + {qasm_gate} q1, q2[0]; + {qasm_gate} q2, q1; +""" parser = QasmParser() q1_0 = cirq.NamedQubit('q1_0') @@ -953,9 +942,7 @@ def test_two_qubit_gates_not_enough_args(qasm_gate: str): parser = QasmParser() - with pytest.raises( - QasmException, match=r".*{}.* takes 2 arg\(s\).*got.*1.*line 5".format(qasm_gate) - ): + with pytest.raises(QasmException, match=rf".*{qasm_gate}.* takes 2 arg\(s\).*got.*1.*line 5"): parser.parse(qasm) @@ -971,7 +958,7 @@ def test_two_qubit_gates_with_too_much_parameters(qasm_gate: str): parser = QasmParser() with pytest.raises( - QasmException, match=r".*{}.* takes 0 parameter\(s\).*got.*1.*line 5".format(qasm_gate) + QasmException, match=rf".*{qasm_gate}.* takes 0 parameter\(s\).*got.*1.*line 5" ): parser.parse(qasm) @@ -981,18 +968,16 @@ def test_two_qubit_gates_with_too_much_parameters(qasm_gate: str): @pytest.mark.parametrize('qasm_gate,cirq_gate', three_qubit_gates) def test_three_qubit_gates(qasm_gate: str, cirq_gate: cirq.testing.TwoQubitGate): - qasm = """ + qasm = f""" OPENQASM 2.0; - include "qelib1.inc"; + include "qelib1.inc"; qreg q1[2]; qreg q2[2]; qreg q3[2]; - {0} q1[0], q1[1], q2[0]; - {0} q1, q2[0], q3[0]; - {0} q1, q2, q3; -""".format( - qasm_gate - ) + {qasm_gate} q1[0], q1[1], q2[0]; + {qasm_gate} q1, q2[0], q3[0]; + {qasm_gate} q1, q2, q3; +""" parser = QasmParser() q1_0 = cirq.NamedQubit('q1_0') @@ -1031,9 +1016,7 @@ def test_three_qubit_gates_not_enough_args(qasm_gate: str): parser = QasmParser() - with pytest.raises( - QasmException, match=r""".*{}.* takes 3 arg\(s\).*got.*1.*line 4""".format(qasm_gate) - ): + with pytest.raises(QasmException, match=rf".*{qasm_gate}.* takes 3 arg\(s\).*got.*1.*line 4"): parser.parse(qasm) @@ -1047,20 +1030,18 @@ def test_three_qubit_gates_with_too_much_parameters(qasm_gate: str): parser = QasmParser() - with pytest.raises(QasmException, match=r""".*{}.*parameter.*line 4.*""".format(qasm_gate)): + with pytest.raises(QasmException, match=f".*{qasm_gate}.*parameter.*line 4.*"): parser.parse(qasm) @pytest.mark.parametrize('qasm_gate,cirq_gate', single_qubit_gates) def test_single_qubit_gates(qasm_gate: str, cirq_gate: cirq.Gate): - qasm = """OPENQASM 2.0; + qasm = f"""OPENQASM 2.0; include "qelib1.inc"; qreg q[2]; - {0} q[0]; - {0} q; - """.format( - qasm_gate - ) + {qasm_gate} q[0]; + {qasm_gate} q; + """ parser = QasmParser() diff --git a/cirq-core/cirq/contrib/qcircuit/qcircuit_test.py b/cirq-core/cirq/contrib/qcircuit/qcircuit_test.py index 7938e65df70..a6f7f408612 100644 --- a/cirq-core/cirq/contrib/qcircuit/qcircuit_test.py +++ b/cirq-core/cirq/contrib/qcircuit/qcircuit_test.py @@ -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 cirq import cirq.contrib.qcircuit as ccq import cirq.testing as ct @@ -36,17 +33,13 @@ def assert_has_qcircuit_diagram(actual: cirq.Circuit, desired: str, **kwargs) -> "Circuit's qcircuit diagram differs from the desired diagram.\n" '\n' 'Diagram of actual circuit:\n' - '{}\n' + f'{actual_diagram}\n' '\n' 'Desired qcircuit diagram:\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' ) diff --git a/cirq-core/cirq/contrib/quirk/quirk_gate.py b/cirq-core/cirq/contrib/quirk/quirk_gate.py index 7c964167ff8..c8bf16f6c52 100644 --- a/cirq-core/cirq/contrib/quirk/quirk_gate.py +++ b/cirq-core/cirq/contrib/quirk/quirk_gate.py @@ -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, cast, Dict, Optional, Union import numpy as np @@ -114,6 +111,7 @@ def single_qubit_matrix_gate(matrix: Optional[np.ndarray]) -> Optional[QuirkOp]: if matrix is None or matrix.shape[0] != 2: return None + # pylint: disable=consider-using-f-string matrix = matrix.round(6) matrix_repr = '{{%s+%si,%s+%si},{%s+%si,%s+%si}}' % ( np.real(matrix[0, 0]), diff --git a/cirq-core/cirq/devices/noise_model.py b/cirq-core/cirq/devices/noise_model.py index 7126792bca5..8a564f2ae89 100644 --- a/cirq-core/cirq/devices/noise_model.py +++ b/cirq-core/cirq/devices/noise_model.py @@ -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, Dict, Iterable, Sequence, TYPE_CHECKING, Union, Callable from cirq import ops, protocols, value @@ -76,7 +73,7 @@ def from_noise_model_like(cls, noise: 'cirq.NOISE_MODEL_LIKE') -> 'cirq.NoiseMod raise TypeError( 'Expected a NOISE_MODEL_LIKE (None, a cirq.NoiseModel, ' - 'or a single qubit gate). Got {!r}'.format(noise) + f'or a single qubit gate). Got {noise!r}' ) def is_virtual_moment(self, moment: 'cirq.Moment') -> bool: diff --git a/cirq-core/cirq/linalg/diagonalize_test.py b/cirq-core/cirq/linalg/diagonalize_test.py index 100fabb6470..10843dd408f 100644 --- a/cirq-core/cirq/linalg/diagonalize_test.py +++ b/cirq-core/cirq/linalg/diagonalize_test.py @@ -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 random from typing import Tuple, Optional @@ -63,8 +60,9 @@ def random_bi_diagonalizable_pair( def _get_assert_diagonalized_by_str(m, p, d): - return 'm.round(3) : {}, p.round(3) : {}, np.abs(p.T @ m @ p).round(2): {}'.format( - np.round(m, 3), np.round(p, 3), np.abs(d).round(2) + return ( + f'm.round(3) : {np.round(m, 3)}, p.round(3) : {np.round(p, 3)}, ' + f'np.abs(p.T @ m @ p).round(2): {np.abs(d).round(2)}' ) @@ -78,10 +76,8 @@ def assert_diagonalized_by(m, p, atol: float = 1e-8): def _get_assert_bidiagonalized_by_str(m, p, q, d): return ( - 'm.round(3) : {}, p.round(3) : {}, q.round(3): {}, ' - 'np.abs(p.T @ m @ p).round(2): {}'.format( - np.round(m, 3), np.round(p, 3), np.round(q, 3), np.abs(d).round(2) - ) + f'm.round(3) : {np.round(m, 3)}, p.round(3) : {np.round(p, 3)}, ' + f'q.round(3): {np.round(q, 3)}, np.abs(p.T @ m @ p).round(2): {np.abs(d).round(2)}' ) diff --git a/cirq-core/cirq/linalg/transformations.py b/cirq-core/cirq/linalg/transformations.py index 54cd9be06c4..9a9f8942fdc 100644 --- a/cirq-core/cirq/linalg/transformations.py +++ b/cirq-core/cirq/linalg/transformations.py @@ -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 - """Utility methods for transforming matrices or vectors.""" import dataclasses @@ -404,13 +401,13 @@ def partial_trace(tensor: np.ndarray, keep_indices: Sequence[int]) -> np.ndarray ndim = tensor.ndim // 2 if not all(tensor.shape[i] == tensor.shape[i + ndim] for i in range(ndim)): raise ValueError( - 'Tensors must have shape (d_0,...,d_{{k-1}},d_0,...,' - 'd_{{k-1}}) but had shape ({}).'.format(tensor.shape) + f'Tensors must have shape (d_0,...,d_{{k-1}},d_0,...,' + f'd_{{k-1}}) but had shape ({tensor.shape}).' ) if not all(i < ndim for i in keep_indices): raise ValueError( - 'keep_indices were {} but must be in first half, ' - 'i.e. have index less that {}.'.format(keep_indices, ndim) + f'keep_indices were {keep_indices} but must be in first half, ' + f'i.e. have index less that {ndim}.' ) keep_set = set(keep_indices) keep_map = dict(zip(keep_indices, sorted(keep_indices))) @@ -535,8 +532,8 @@ def sub_state_vector( if not np.log2(state_vector.size).is_integer(): raise ValueError( - "Input state_vector of size {} does not represent a " - "state over qubits.".format(state_vector.size) + f"Input state_vector of size {state_vector.size} does not represent a " + "state over qubits." ) n_qubits = int(np.log2(state_vector.size)) @@ -577,8 +574,7 @@ def sub_state_vector( return default raise EntangledStateError( - "Input state vector could not be factored into pure state over " - "indices {}".format(keep_indices) + f"Input state vector could not be factored into pure state over indices {keep_indices}" ) diff --git a/cirq-core/cirq/ops/clifford_gate.py b/cirq-core/cirq/ops/clifford_gate.py index 3495d97f666..7a53b40ee4b 100644 --- a/cirq-core/cirq/ops/clifford_gate.py +++ b/cirq-core/cirq/ops/clifford_gate.py @@ -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, Dict, List, Optional, Sequence, Tuple, TYPE_CHECKING, Union @@ -94,6 +91,7 @@ def _validate_map_input( ' of x_to, y_to, and z_to but both were given' ) if len(pauli_map_to) != required_transform_count: + # pylint: disable=consider-using-f-string raise ValueError( 'Method takes {} transform{} but {} {} given'.format( required_transform_count, diff --git a/cirq-core/cirq/ops/common_gate_families.py b/cirq-core/cirq/ops/common_gate_families.py index 77c4b90f8c8..f195511c171 100644 --- a/cirq-core/cirq/ops/common_gate_families.py +++ b/cirq-core/cirq/ops/common_gate_families.py @@ -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 - """Common Gate Families used in cirq-core""" from typing import Any, cast, Optional, Type, Union @@ -40,9 +37,8 @@ def __init__(self, num_qubits: Optional[int] = None) -> None: self._num_qubits = num_qubits name = f'{str(num_qubits) if num_qubits else "Any"}-Qubit UnitaryGateFamily' - description = 'Accepts any {}unitary gate'.format( - f'{num_qubits}-qubit ' if num_qubits else '' - ) + kind = f'{num_qubits}-qubit ' if num_qubits else '' + description = f'Accepts any {kind}unitary gate' super().__init__(raw_types.Gate, name=name, description=description) def _predicate(self, g: raw_types.Gate) -> bool: diff --git a/cirq-core/cirq/ops/common_gates.py b/cirq-core/cirq/ops/common_gates.py index 815623ce683..af259c6d19b 100644 --- a/cirq-core/cirq/ops/common_gates.py +++ b/cirq-core/cirq/ops/common_gates.py @@ -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 - """Quantum gates that are commonly used in the literature. This module creates Gate instances for the following gates: @@ -516,8 +513,10 @@ def __repr__(self) -> str: if self._exponent == 1: return 'cirq.Y' return f'(cirq.Y**{proper_repr(self._exponent)})' - return 'cirq.YPowGate(exponent={}, global_shift={!r})'.format( - proper_repr(self._exponent), self._global_shift + return ( + 'cirq.YPowGate(' + f'exponent={proper_repr(self._exponent)}, ' + f'global_shift={self._global_shift!r})' ) @@ -1225,8 +1224,10 @@ def __repr__(self) -> str: if self._exponent == 1: return 'cirq.CZ' return f'(cirq.CZ**{proper_repr(self._exponent)})' - return 'cirq.CZPowGate(exponent={}, global_shift={!r})'.format( - proper_repr(self._exponent), self._global_shift + return ( + 'cirq.CZPowGate(' + f'exponent={proper_repr(self._exponent)}, ' + f'global_shift={self._global_shift!r})' ) diff --git a/cirq-core/cirq/ops/diagonal_gate.py b/cirq-core/cirq/ops/diagonal_gate.py index d412e8baedc..ec5e6ad44d0 100644 --- a/cirq-core/cirq/ops/diagonal_gate.py +++ b/cirq-core/cirq/ops/diagonal_gate.py @@ -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 - """Creates the gate instance for any number qubits diagonal gate. The gate is used to create a (2^n)x(2^n) matrix with the diagonal elements @@ -150,7 +147,7 @@ def _circuit_diagram_info_( diag_str += ', '.join(proper_repr(angle) for angle in rounded_angles[-2:]) diag_str = f'diag({diag_str})' return protocols.CircuitDiagramInfo( - [diag_str] + ['#' + str(i) for i in range(2, self._num_qubits_() + 1)] + [diag_str] + [f"#{i}" for i in range(2, self._num_qubits_() + 1)] ) def __pow__(self, exponent: Any) -> 'DiagonalGate': @@ -216,6 +213,5 @@ def _json_dict_(self) -> Dict[str, Any]: return protocols.obj_to_dict_helper(self, attribute_names=["diag_angles_radians"]) def __repr__(self) -> str: - return 'cirq.DiagonalGate([{}])'.format( - ','.join(proper_repr(angle) for angle in self._diag_angles_radians) - ) + angles = ','.join(proper_repr(angle) for angle in self._diag_angles_radians) + return f'cirq.DiagonalGate([{angles}])' diff --git a/cirq-core/cirq/ops/gateset_test.py b/cirq-core/cirq/ops/gateset_test.py index 0e24e63ec48..6bdc52000ef 100644 --- a/cirq-core/cirq/ops/gateset_test.py +++ b/cirq-core/cirq/ops/gateset_test.py @@ -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 Tuple, List, cast import re import pytest @@ -40,8 +37,10 @@ def __repr__(self) -> str: if self._exponent == 1: return 'cirq.ops.gateset_test.CustomX' return f'(cirq.ops.gateset_test.CustomX**{proper_repr(self._exponent)})' - return 'cirq.ops.gateset_test.CustomXPowGate(exponent={}, global_shift={!r})'.format( - proper_repr(self._exponent), self._global_shift + return ( + 'cirq.ops.gateset_test.CustomXPowGate(' + f'exponent={proper_repr(self._exponent)}, ' + f'global_shift={self._global_shift!r})' ) def _num_qubits_(self) -> int: diff --git a/cirq-core/cirq/ops/linear_combinations.py b/cirq-core/cirq/ops/linear_combinations.py index 1c9f82cd9d3..9f50216dab9 100644 --- a/cirq-core/cirq/ops/linear_combinations.py +++ b/cirq-core/cirq/ops/linear_combinations.py @@ -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 collections import defaultdict from typing import ( AbstractSet, @@ -655,7 +652,7 @@ def expectation_from_state_vector( if any(abs(p.coefficient.imag) > 0.0001 for p in self): raise NotImplementedError( "Cannot compute expectation value of a non-Hermitian " - "PauliString <{}>. Coefficient must be real.".format(self) + f"PauliString <{self}>. Coefficient must be real." ) # TODO: Avoid enforce specific complex type. This is necessary to @@ -717,7 +714,7 @@ def expectation_from_density_matrix( if any(abs(p.coefficient.imag) > 0.0001 for p in self): raise NotImplementedError( "Cannot compute expectation value of a non-Hermitian " - "PauliString <{}>. Coefficient must be real.".format(self) + f"PauliString <{self}>. Coefficient must be real." ) # FIXME: Avoid enforce specific complex type. This is necessary to diff --git a/cirq-core/cirq/ops/raw_types.py b/cirq-core/cirq/ops/raw_types.py index e5fd9825fbc..9366254581b 100644 --- a/cirq-core/cirq/ops/raw_types.py +++ b/cirq-core/cirq/ops/raw_types.py @@ -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 - """Basic types defining qubits, gates, and operations.""" import abc @@ -1045,15 +1042,13 @@ def _validate_qid_shape(val: Any, qubits: Sequence['cirq.Qid']) -> None: qid_shape = protocols.qid_shape(val) if len(qubits) != len(qid_shape): raise ValueError( - 'Wrong number of qubits for <{!r}>. ' - 'Expected {} qubits but got <{!r}>.'.format(val, len(qid_shape), qubits) + f'Wrong number of qubits for <{val!r}>. ' + f'Expected {len(qid_shape)} qubits but got <{qubits!r}>.' ) if any(qid.dimension != dimension for qid, dimension in zip(qubits, qid_shape)): raise ValueError( - 'Wrong shape of qids for <{!r}>. ' - 'Expected {} but got {} <{!r}>.'.format( - val, qid_shape, tuple(qid.dimension for qid in qubits), qubits - ) + f'Wrong shape of qids for <{val!r}>. ' + f'Expected {qid_shape} but got {tuple(qid.dimension for qid in qubits)} <{qubits!r}>.' ) if len(set(qubits)) != len(qubits): raise ValueError( diff --git a/cirq-core/cirq/ops/three_qubit_gates.py b/cirq-core/cirq/ops/three_qubit_gates.py index 635ace70139..03795728f10 100644 --- a/cirq-core/cirq/ops/three_qubit_gates.py +++ b/cirq-core/cirq/ops/three_qubit_gates.py @@ -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 - """Common quantum gates that target three qubits.""" from typing import ( @@ -179,8 +176,9 @@ def __repr__(self) -> str: if self._exponent == 1: return 'cirq.CCZ' return f'(cirq.CCZ**{proper_repr(self._exponent)})' - return 'cirq.CCZPowGate(exponent={}, global_shift={!r})'.format( - proper_repr(self._exponent), self._global_shift + return ( + f'cirq.CCZPowGate(exponent={proper_repr(self._exponent)}, ' + f'global_shift={self._global_shift!r})' ) def __str__(self) -> str: @@ -386,9 +384,8 @@ def _json_dict_(self) -> Dict[str, Any]: return protocols.obj_to_dict_helper(self, attribute_names=["diag_angles_radians"]) def __repr__(self) -> str: - return 'cirq.ThreeQubitDiagonalGate([{}])'.format( - ','.join(proper_repr(angle) for angle in self._diag_angles_radians) - ) + angles = ','.join(proper_repr(angle) for angle in self._diag_angles_radians) + return f'cirq.ThreeQubitDiagonalGate([{angles}])' def _num_qubits_(self) -> int: return 3 @@ -491,8 +488,9 @@ def __repr__(self) -> str: if self._exponent == 1: return 'cirq.TOFFOLI' return f'(cirq.TOFFOLI**{proper_repr(self._exponent)})' - return 'cirq.CCXPowGate(exponent={}, global_shift={!r})'.format( - proper_repr(self._exponent), self._global_shift + return ( + f'cirq.CCXPowGate(exponent={proper_repr(self._exponent)}, ' + f'global_shift={self._global_shift!r})' ) def __str__(self) -> str: diff --git a/cirq-core/cirq/ops/two_qubit_diagonal_gate.py b/cirq-core/cirq/ops/two_qubit_diagonal_gate.py index 84f7f169dcd..7b7e34ebc9f 100644 --- a/cirq-core/cirq/ops/two_qubit_diagonal_gate.py +++ b/cirq-core/cirq/ops/two_qubit_diagonal_gate.py @@ -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 - """Creates the gate instance for a two qubit diagonal gate. The gate is used to create a 4x4 matrix with the diagonal elements @@ -138,9 +135,8 @@ def _value_equality_values_(self) -> Any: return tuple(self._diag_angles_radians) def __repr__(self) -> str: - return 'cirq.TwoQubitDiagonalGate([{}])'.format( - ','.join(proper_repr(angle) for angle in self._diag_angles_radians) - ) + angles = ','.join(proper_repr(angle) for angle in self._diag_angles_radians) + return f'cirq.TwoQubitDiagonalGate([{angles}])' def _json_dict_(self) -> Dict[str, Any]: return protocols.obj_to_dict_helper(self, attribute_names=["diag_angles_radians"]) diff --git a/cirq-core/cirq/protocols/apply_channel_protocol.py b/cirq-core/cirq/protocols/apply_channel_protocol.py index 9211f89828c..cd1a58b75d1 100644 --- a/cirq-core/cirq/protocols/apply_channel_protocol.py +++ b/cirq-core/cirq/protocols/apply_channel_protocol.py @@ -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 protocol for implementing high performance channel evolutions.""" from typing import Any, Iterable, Optional, Sequence, TypeVar, Tuple, Union @@ -228,13 +225,13 @@ def apply_channel( raise ValueError( 'Invalid target_tensor shape or selected axes. ' 'The selected left and right shape of target_tensor ' - 'are not equal. Got {!r} and {!r}.'.format(left_shape, right_shape) + f'are not equal. Got {left_shape!r} and {right_shape!r}.' ) if val_qid_shape != left_shape: raise ValueError( 'Invalid channel qid shape is not equal to the ' 'selected left and right shape of target_tensor. ' - 'Got {!r} but expected {!r}.'.format(val_qid_shape, left_shape) + f'Got {val_qid_shape!r} but expected {left_shape!r}.' ) # Check if the specialized method is present. @@ -244,9 +241,9 @@ def apply_channel( def err_str(buf_num_str): return ( - "Object of type '{}' returned a result object equal to " - "auxiliary_buffer{}. This type violates the contract " - "that appears in apply_channel's documentation.".format(type(val), buf_num_str) + f"Object of type '{type(val)}' returned a result object equal to " + f"auxiliary_buffer{buf_num_str}. This type violates the contract " + "that appears in apply_channel's documentation." ) assert result is not args.auxiliary_buffer0, err_str('0') @@ -267,9 +264,9 @@ def err_str(buf_num_str): if default is not RaiseTypeErrorIfNotProvided: return default raise TypeError( - "object of type '{}' has no _apply_channel_, _apply_unitary_, " + f"object of type '{type(val)}' has no _apply_channel_, _apply_unitary_, " "_unitary_, or _kraus_ methods (or they returned None or " - "NotImplemented).".format(type(val)) + "NotImplemented)." ) diff --git a/cirq-core/cirq/protocols/apply_mixture_protocol.py b/cirq-core/cirq/protocols/apply_mixture_protocol.py index e7787b2a481..121fc1b6dfd 100644 --- a/cirq-core/cirq/protocols/apply_mixture_protocol.py +++ b/cirq-core/cirq/protocols/apply_mixture_protocol.py @@ -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 protocol for implementing high performance mixture evolutions.""" from typing import Any, cast, Iterable, Optional, Tuple, TypeVar, Union @@ -249,9 +246,9 @@ def apply_mixture( def err_str(buf_num_str): return ( - "Object of type '{}' returned a result object equal to " - "auxiliary_buffer{}. This type violates the contract " - "that appears in apply_mixture's documentation.".format(type(val), buf_num_str) + f"Object of type '{type(val)}' returned a result object equal to " + f"auxiliary_buffer{buf_num_str}. This type violates the contract " + "that appears in apply_mixture's documentation." ) assert result is not args.auxiliary_buffer0, err_str('0') @@ -273,9 +270,8 @@ def err_str(buf_num_str): if default is not RaiseTypeErrorIfNotProvided: return default raise TypeError( - "object of type '{}' has no _apply_mixture_, _apply_unitary_, " - "_unitary_, or _mixture_ methods (or they returned None or " - "NotImplemented).".format(type(val)) + f"object of type '{type(val)}' has no _apply_mixture_, _apply_unitary_, " + "_unitary_, or _mixture_ methods (or they returned None or NotImplemented)." ) @@ -291,7 +287,7 @@ def _validate_input(val: Any, args: 'ApplyMixtureArgs') -> Tuple[Any, 'ApplyMixt raise ValueError( 'Invalid mixture qid shape is not equal to the ' 'selected left and right shape of target_tensor. ' - 'Got {!r} but expected {!r}.'.format(val_qid_shape, left_shape) + f'Got {val_qid_shape!r} but expected {left_shape!r}.' ) if args.right_axes is not None: @@ -302,7 +298,7 @@ def _validate_input(val: Any, args: 'ApplyMixtureArgs') -> Tuple[Any, 'ApplyMixt raise ValueError( 'Invalid target_tensor shape or selected axes. ' 'The selected left and right shape of ' - 'target_tensor are not equal. Got {!r} and {!r}.'.format(left_shape, right_shape) + f'target_tensor are not equal. Got {left_shape!r} and {right_shape!r}.' ) return val, args, is_density_matrix diff --git a/cirq-core/cirq/protocols/apply_unitary_protocol.py b/cirq-core/cirq/protocols/apply_unitary_protocol.py index 58293cbf3f7..c3adaaaab1c 100644 --- a/cirq-core/cirq/protocols/apply_unitary_protocol.py +++ b/cirq-core/cirq/protocols/apply_unitary_protocol.py @@ -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 protocol for implementing high performance unitary left-multiplies.""" import warnings @@ -408,8 +405,8 @@ def apply_unitary( "cirq.apply_unitary failed. " "Value doesn't have a (non-parameterized) unitary effect.\n" "\n" - "type: {}\n" - "value: {!r}\n" + f"type: {type(unitary_value)}\n" + f"value: {unitary_value!r}\n" "\n" "The value failed to satisfy any of the following criteria:\n" "- An `_apply_unitary_(self, args) method that returned a value " @@ -418,7 +415,6 @@ def apply_unitary( "besides None or NotImplemented.\n" "- A `_decompose_(self)` method that returned a " "list of unitary operations.\n" - "".format(type(unitary_value), unitary_value) ) @@ -579,8 +575,8 @@ def apply_unitaries( "There was a non-unitary value in the `unitary_values` " "list.\n" "\n" - "non-unitary value type: {}\n" - "non-unitary value: {!r}".format(type(op), op) + f"non-unitary value type: {type(op)}\n" + f"non-unitary value: {op!r}" ) return default diff --git a/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py b/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py index f3eebe4f6b4..e54f0e8d2db 100644 --- a/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py +++ b/cirq-core/cirq/protocols/circuit_diagram_info_protocol.py @@ -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 re from fractions import Fraction from typing import ( @@ -122,7 +119,7 @@ def _wire_symbols_including_formatted_exponent( else: ks = (0,) for k in ks: - result[k] += '^' + exponent + result[k] += f"^{exponent}" return result def _formatted_exponent(self, args: 'cirq.CircuitDiagramInfoArgs') -> Optional[str]: @@ -274,7 +271,7 @@ def format_radians(self, radians: Union[sympy.Basic, int, float]) -> str: if radians == 0: return '0' if radians == -np.pi: - return '-' + unit + return f"-{unit}" if self.precision is not None and not isinstance(radians, sympy.Basic): quantity = self.format_real(radians / np.pi) return quantity + unit @@ -434,8 +431,8 @@ def circuit_diagram_info( if getter is None: raise TypeError(f"object of type '{type(val)}' has no _circuit_diagram_info_ method.") raise TypeError( - "object of type '{}' does have a _circuit_diagram_info_ " - "method, but it returned NotImplemented.".format(type(val)) + f"object of type '{type(val)}' does have a _circuit_diagram_info_ " + "method, but it returned NotImplemented." ) diff --git a/cirq-core/cirq/protocols/inverse_protocol.py b/cirq-core/cirq/protocols/inverse_protocol.py index 6794ed0b742..f54b4099836 100644 --- a/cirq-core/cirq/protocols/inverse_protocol.py +++ b/cirq-core/cirq/protocols/inverse_protocol.py @@ -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, List, overload, Tuple, TYPE_CHECKING, TypeVar, Union, Iterable from cirq import ops @@ -118,9 +115,9 @@ def inverse(val: Any, default: Any = RaiseTypeErrorIfNotProvided) -> Any: if default is not RaiseTypeErrorIfNotProvided: return default raise TypeError( - "object of type '{}' isn't invertible. " + f"object of type '{type(val)}' isn't invertible. " "It has no __pow__ method (or the method returned NotImplemented) " - "and it isn't an iterable of invertible objects.".format(type(val)) + "and it isn't an iterable of invertible objects." ) diff --git a/cirq-core/cirq/protocols/kraus_protocol.py b/cirq-core/cirq/protocols/kraus_protocol.py index aabd5777a1c..bc661e5633d 100644 --- a/cirq-core/cirq/protocols/kraus_protocol.py +++ b/cirq-core/cirq/protocols/kraus_protocol.py @@ -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 - """Protocol and methods for obtaining Kraus representation of quantum channels.""" from typing import Any, Sequence, Tuple, TypeVar, Union @@ -167,13 +164,12 @@ def kraus( if kraus_getter is None and unitary_getter is None and mixture_getter is None: raise TypeError( - "object of type '{}' has no _kraus_ or _mixture_ or " - "_unitary_ method.".format(type(val)) + f"object of type '{type(val)}' has no _kraus_ or _mixture_ or _unitary_ method." ) raise TypeError( - "object of type '{}' does have a _kraus_, _mixture_ or " - "_unitary_ method, but it returned NotImplemented.".format(type(val)) + f"object of type '{type(val)}' does have a _kraus_, _mixture_ or " + "_unitary_ method, but it returned NotImplemented." ) diff --git a/cirq-core/cirq/protocols/mixture_protocol.py b/cirq-core/cirq/protocols/mixture_protocol.py index 1e2fe22873c..5b3b79ae93e 100644 --- a/cirq-core/cirq/protocols/mixture_protocol.py +++ b/cirq-core/cirq/protocols/mixture_protocol.py @@ -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 - """Protocol for objects that are mixtures (probabilistic combinations).""" from typing import Any, Sequence, Tuple, Union @@ -107,8 +104,8 @@ def mixture( raise TypeError(f"object of type '{type(val)}' has no _mixture_ or _unitary_ method.") raise TypeError( - "object of type '{}' does have a _mixture_ or _unitary_ " - "method, but it returned NotImplemented.".format(type(val)) + f"object of type '{type(val)}' does have a _mixture_ or _unitary_ " + "method, but it returned NotImplemented." ) diff --git a/cirq-core/cirq/protocols/phase_protocol.py b/cirq-core/cirq/protocols/phase_protocol.py index 42bced3142e..84a49db6da8 100644 --- a/cirq-core/cirq/protocols/phase_protocol.py +++ b/cirq-core/cirq/protocols/phase_protocol.py @@ -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, TypeVar from typing_extensions import Protocol @@ -91,6 +88,6 @@ def phase_by( if getter is None: raise TypeError(f"object of type '{type(val)}' has no _phase_by_ method.") raise TypeError( - "object of type '{}' does have a _phase_by_ method, " - "but it returned NotImplemented.".format(type(val)) + f"object of type '{type(val)}' does have a _phase_by_ method, " + "but it returned NotImplemented." ) diff --git a/cirq-core/cirq/protocols/pow_protocol.py b/cirq-core/cirq/protocols/pow_protocol.py index 9840abb54ca..3ad2605870f 100644 --- a/cirq-core/cirq/protocols/pow_protocol.py +++ b/cirq-core/cirq/protocols/pow_protocol.py @@ -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, Optional, overload, TypeVar, TYPE_CHECKING, Union if TYPE_CHECKING: @@ -97,8 +94,7 @@ def pow(val: Any, exponent: Any, default: Any = RaiseTypeErrorIfNotProvided) -> if raiser is None: raise TypeError(f"object of type '{type(val)}' has no __pow__ method.") raise TypeError( - "object of type '{}' does have a __pow__ method, " - "but it returned NotImplemented.".format(type(val)) + f"object of type '{type(val)}' does have a __pow__ method, but it returned NotImplemented." ) diff --git a/cirq-core/cirq/protocols/qasm.py b/cirq-core/cirq/protocols/qasm.py index 145c6de4eed..9988df79b94 100644 --- a/cirq-core/cirq/protocols/qasm.py +++ b/cirq-core/cirq/protocols/qasm.py @@ -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 string from typing import TYPE_CHECKING, Union, Any, Tuple, TypeVar, Optional, Dict, Iterable @@ -175,8 +172,8 @@ def qasm( if method is None: raise TypeError(f"object of type '{type(val)}' has no _qasm_ method.") raise TypeError( - "object of type '{}' does have a _qasm_ method, " - "but it returned NotImplemented or None.".format(type(val)) + f"object of type '{type(val)}' does have a _qasm_ method, " + "but it returned NotImplemented or None." ) diff --git a/cirq-core/cirq/protocols/qid_shape_protocol.py b/cirq-core/cirq/protocols/qid_shape_protocol.py index 5349d39c80c..8f2e1f8c331 100644 --- a/cirq-core/cirq/protocols/qid_shape_protocol.py +++ b/cirq-core/cirq/protocols/qid_shape_protocol.py @@ -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, Sequence, Tuple, TypeVar, Union from typing_extensions import Protocol @@ -126,13 +123,13 @@ def qid_shape( if getter is not None: raise TypeError( - "object of type '{}' does have a _qid_shape_ method, " - "but it returned NotImplemented.".format(type(val)) + f"object of type '{type(val)}' does have a _qid_shape_ method, " + "but it returned NotImplemented." ) if num_getter is not None: raise TypeError( - "object of type '{}' does have a _num_qubits_ method, " - "but it returned NotImplemented.".format(type(val)) + f"object of type '{type(val)}' does have a _num_qubits_ method, " + "but it returned NotImplemented." ) raise TypeError(f"object of type '{type(val)}' has no _num_qubits_ or _qid_shape_ methods.") @@ -181,12 +178,12 @@ def num_qubits( if num_getter is not None: raise TypeError( - "object of type '{}' does have a _num_qubits_ method, " - "but it returned NotImplemented.".format(type(val)) + f"object of type '{type(val)}' does have a _num_qubits_ method, " + "but it returned NotImplemented." ) if getter is not None: raise TypeError( - "object of type '{}' does have a _qid_shape_ method, " - "but it returned NotImplemented.".format(type(val)) + f"object of type '{type(val)}' does have a _qid_shape_ method, " + "but it returned NotImplemented." ) raise TypeError(f"object of type '{type(val)}' has no _num_qubits_ or _qid_shape_ methods.") diff --git a/cirq-core/cirq/protocols/unitary_protocol.py b/cirq-core/cirq/protocols/unitary_protocol.py index d56e02d2d2f..38de4043dbc 100644 --- a/cirq-core/cirq/protocols/unitary_protocol.py +++ b/cirq-core/cirq/protocols/unitary_protocol.py @@ -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, TypeVar, Union, Optional import numpy as np @@ -130,8 +127,8 @@ def unitary( "cirq.unitary failed. " "Value doesn't have a (non-parameterized) unitary effect.\n" "\n" - "type: {}\n" - "value: {!r}\n" + f"type: {type(val)}\n" + f"value: {val!r}\n" "\n" "The value failed to satisfy any of the following criteria:\n" "- A `_unitary_(self)` method that returned a value " @@ -139,7 +136,7 @@ def unitary( "- A `_decompose_(self)` method that returned a " "list of unitary operations.\n" "- An `_apply_unitary_(self, args) method that returned a value " - "besides None or NotImplemented.".format(type(val), val) + "besides None or NotImplemented." ) diff --git a/cirq-core/cirq/qis/clifford_tableau.py b/cirq-core/cirq/qis/clifford_tableau.py index 026919ac8bf..d278e050f41 100644 --- a/cirq-core/cirq/qis/clifford_tableau.py +++ b/cirq-core/cirq/qis/clifford_tableau.py @@ -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 abc from typing import Any, Dict, List, Optional, Sequence, TYPE_CHECKING import numpy as np @@ -340,11 +337,11 @@ def _str_full_(self) -> str: for k in range(self.n): if self.xs[i, k] & (not self.zs[i, k]): - string += 'X%d' % k + string += f'X{k}' elif (not self.xs[i, k]) & self.zs[i, k]: - string += 'Z%d' % k + string += f'Z{k}' elif self.xs[i, k] & self.zs[i, k]: - string += 'Y%d' % k + string += f'Y{k}' else: string += ' ' diff --git a/cirq-core/cirq/qis/states.py b/cirq-core/cirq/qis/states.py index e132139ff00..9b8c420ebec 100644 --- a/cirq-core/cirq/qis/states.py +++ b/cirq-core/cirq/qis/states.py @@ -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 - """Classes and methods for quantum states.""" from typing import Any, cast, Iterable, List, Optional, Sequence, Set, TYPE_CHECKING, Tuple, Union @@ -729,9 +726,8 @@ def dirac_notation( if len(state_vector) != np.prod(qid_shape, dtype=np.int64): raise ValueError( - 'state_vector has incorrect size. Expected {} but was {}.'.format( - np.prod(qid_shape, dtype=np.int64), len(state_vector) - ) + 'state_vector has incorrect size. ' + f'Expected {np.prod(qid_shape, dtype=np.int64)} but was {len(state_vector)}.' ) digit_separator = '' if max(qid_shape, default=0) < 10 else ',' @@ -824,8 +820,8 @@ def to_valid_state_vector( num_qubits = len(qid_shape) if num_qubits != len(qid_shape): raise ValueError( - 'num_qubits != len(qid_shape). num_qubits is <{!r}>. ' - 'qid_shape is <{!r}>.'.format(num_qubits, qid_shape) + f'num_qubits != len(qid_shape). num_qubits is <{num_qubits!r}>. ' + f'qid_shape is <{qid_shape!r}>.' ) if isinstance(state_rep, np.ndarray): @@ -886,15 +882,12 @@ def validate_normalized_state_vector( """ if dtype and state_vector.dtype != dtype: raise ValueError( - 'state_vector has invalid dtype. Expected {} but was {}'.format( - dtype, state_vector.dtype - ) + f'state_vector has invalid dtype. Expected {dtype} but was {state_vector.dtype}' ) if state_vector.size != np.prod(qid_shape, dtype=np.int64): raise ValueError( - 'state_vector has incorrect size. Expected {} but was {}.'.format( - np.prod(qid_shape, dtype=np.int64), state_vector.size - ) + 'state_vector has incorrect size. ' + f'Expected {np.prod(qid_shape, dtype=np.int64)} but was {state_vector.size}.' ) norm = np.sum(np.abs(state_vector) ** 2) if not np.isclose(norm, 1, atol=atol): @@ -919,8 +912,8 @@ def validate_qid_shape( qid_shape = (2,) * (size.bit_length() - 1) if size != np.prod(qid_shape, dtype=np.int64): raise ValueError( - 'state_vector.size ({}) is not a power of two or is not a product ' - 'of the qid shape {!r}.'.format(size, qid_shape) + f'state_vector.size ({size}) is not a power of two or is not a product ' + f'of the qid shape {qid_shape!r}.' ) return qid_shape @@ -1046,8 +1039,8 @@ def _qid_shape_from_args( return (2,) * num_qubits if len(qid_shape) != num_qubits: raise ValueError( - 'num_qubits != len(qid_shape). num_qubits was {!r}. ' - 'qid_shape was {!r}.'.format(num_qubits, qid_shape) + f'num_qubits != len(qid_shape). num_qubits was {num_qubits!r}. ' + f'qid_shape was {qid_shape!r}.' ) return qid_shape diff --git a/cirq-core/cirq/sim/clifford/clifford_simulator.py b/cirq-core/cirq/sim/clifford/clifford_simulator.py index e60f535fd9c..bb377a54770 100644 --- a/cirq-core/cirq/sim/clifford/clifford_simulator.py +++ b/cirq-core/cirq/sim/clifford/clifford_simulator.py @@ -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 - """An efficient simulator for Clifford circuits. Allowed operations include: @@ -262,8 +259,8 @@ def apply_measurement( ): if not isinstance(op.gate, cirq.MeasurementGate): raise TypeError( - 'apply_measurement only supports cirq.MeasurementGate operations. Found %s instead.' - % str(op.gate) + f'apply_measurement only supports cirq.MeasurementGate operations. ' + f'Found {op.gate} instead.' ) if collapse_state_vector: diff --git a/cirq-core/cirq/sim/density_matrix_simulation_state.py b/cirq-core/cirq/sim/density_matrix_simulation_state.py index c3d6e3365c2..b3c087a2641 100644 --- a/cirq-core/cirq/sim/density_matrix_simulation_state.py +++ b/cirq-core/cirq/sim/density_matrix_simulation_state.py @@ -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 - """Objects and methods for acting efficiently on a density matrix.""" from typing import Any, Callable, List, Optional, Sequence, Tuple, Type, TYPE_CHECKING, Union @@ -309,7 +306,7 @@ def _act_on_fallback_( raise TypeError( "Can't simulate operations that don't implement " "SupportsUnitary, SupportsConsistentApplyUnitary, " - "SupportsMixture or SupportsKraus or is a measurement: {!r}".format(action) + f"SupportsMixture or SupportsKraus or is a measurement: {action!r}" ) def __repr__(self) -> str: diff --git a/cirq-core/cirq/sim/density_matrix_utils.py b/cirq-core/cirq/sim/density_matrix_utils.py index 270907bc765..638230ec767 100644 --- a/cirq-core/cirq/sim/density_matrix_utils.py +++ b/cirq-core/cirq/sim/density_matrix_utils.py @@ -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 - """Code to handle density matrices.""" from typing import List, Optional, TYPE_CHECKING, Tuple, Sequence @@ -207,10 +204,8 @@ def _validate_density_matrix_qid_shape( if len(shape) == 2: if np.prod(qid_shape, dtype=np.int64) ** 2 != np.prod(shape, dtype=np.int64): raise ValueError( - 'Matrix size does not match qid shape {!r}. Got matrix with ' - 'shape {!r}. Expected {!r}.'.format( - qid_shape, shape, np.prod(qid_shape, dtype=np.int64) - ) + f'Matrix size does not match qid shape {qid_shape!r}. Got matrix with ' + f'shape {shape!r}. Expected {np.prod(qid_shape, dtype=np.int64)!r}.' ) return qid_shape if len(shape) % 2 != 0: @@ -237,12 +232,12 @@ def _validate_num_qubits(density_matrix: np.ndarray) -> int: if row_size & (row_size - 1): raise ValueError( 'Matrix could not be shaped into a square matrix with dimensions ' - 'that are a power of two. Shape was {}'.format(shape) + f'that are a power of two. Shape was {shape}' ) if len(shape) > 2 and not np.allclose(shape, 2): raise ValueError( 'Matrix is a tensor of rank greater than 2, but had dimensions ' - 'that are not powers of two. Shape was {}'.format(shape) + f'that are not powers of two. Shape was {shape}' ) return int(row_size).bit_length() - 1 diff --git a/cirq-core/cirq/sim/mux.py b/cirq-core/cirq/sim/mux.py index 879bf2cb5f0..02c5ede8d2a 100644 --- a/cirq-core/cirq/sim/mux.py +++ b/cirq-core/cirq/sim/mux.py @@ -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 - """Sampling/simulation methods that delegate to appropriate simulators. Filename is a reference to multiplexing. @@ -163,7 +160,7 @@ def final_state_vector( "because it is not unitary. " "Maybe you wanted `cirq.final_density_matrix`?\n" "\n" - "Program: {!r}".format(circuit_like) + f"Program: {circuit_like!r}" ) result = sparse_simulator.Simulator(dtype=dtype, seed=seed).simulate( diff --git a/cirq-core/cirq/sim/simulator.py b/cirq-core/cirq/sim/simulator.py index 08dea32a410..2608482b6a0 100644 --- a/cirq-core/cirq/sim/simulator.py +++ b/cirq-core/cirq/sim/simulator.py @@ -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 - """Abstract base classes for different types of simulators. Simulator types include: @@ -963,7 +960,7 @@ def check_all_resolved(circuit): unresolved = [op for moment in circuit for op in moment if protocols.is_parameterized(op)] raise ValueError( 'Circuit contains ops whose symbols were not specified in ' - 'parameter sweep. Ops: {}'.format(unresolved) + f'parameter sweep. Ops: {unresolved}' ) diff --git a/cirq-core/cirq/sim/state_vector_simulation_state.py b/cirq-core/cirq/sim/state_vector_simulation_state.py index e25cac118d5..7674e12e873 100644 --- a/cirq-core/cirq/sim/state_vector_simulation_state.py +++ b/cirq-core/cirq/sim/state_vector_simulation_state.py @@ -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 - """Objects and methods for acting efficiently on a state vector.""" from typing import Any, Callable, List, Optional, Sequence, Tuple, Type, TYPE_CHECKING, Union @@ -397,7 +394,7 @@ def _act_on_fallback_( raise TypeError( "Can't simulate operations that don't implement " "SupportsUnitary, SupportsConsistentApplyUnitary, " - "SupportsMixture or is a measurement: {!r}".format(action) + f"SupportsMixture or is a measurement: {action!r}" ) def __repr__(self) -> str: diff --git a/cirq-core/cirq/testing/circuit_compare.py b/cirq-core/cirq/testing/circuit_compare.py index b22d16bd872..74637292f7e 100644 --- a/cirq-core/cirq/testing/circuit_compare.py +++ b/cirq-core/cirq/testing/circuit_compare.py @@ -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, Dict, Iterable, List, Optional, Sequence, Union from collections import defaultdict @@ -179,10 +176,10 @@ def assert_circuits_with_terminal_measurements_are_equivalent( "Circuit's effect differs from the reference circuit.\n" '\n' 'Diagram of actual circuit:\n' - '{}\n' + f'{actual}\n' '\n' 'Diagram of reference circuit with desired function:\n' - '{}\n'.format(actual, reference) + f'{reference}\n' ) @@ -199,20 +196,20 @@ def assert_same_circuits( "Actual circuit differs from expected circuit.\n" "\n" "Diagram of actual circuit:\n" - "{}\n" + f"{actual}\n" "\n" "Diagram of expected circuit:\n" - "{}\n" + f"{expected}\n" "\n" "Index of first differing moment:\n" - "{}\n" + f"{_first_differing_moment_index(actual, expected)}\n" "\n" "Full repr of actual circuit:\n" - "{!r}\n" + f"{actual!r}\n" "\n" "Full repr of expected circuit:\n" - "{!r}\n" - ).format(actual, expected, _first_differing_moment_index(actual, expected), actual, expected) + f"{expected!r}\n" + ) def _first_differing_moment_index( @@ -279,17 +276,13 @@ def assert_has_diagram( "Circuit's text diagram differs from the desired diagram.\n" '\n' 'Diagram of actual circuit:\n' - '{}\n' + f'{actual_diagram}\n' '\n' 'Desired text diagram:\n' - '{}\n' + f'{desired_diagram}\n' '\n' 'Highlighted differences:\n' - '{}\n'.format( - actual_diagram, - desired_diagram, - highlight_text_differences(actual_diagram, desired_diagram), - ) + f'{highlight_text_differences(actual_diagram, desired_diagram)}\n' ) diff --git a/cirq-core/cirq/testing/consistent_act_on.py b/cirq-core/cirq/testing/consistent_act_on.py index 881f12bc6c7..2b006202b1c 100644 --- a/cirq-core/cirq/testing/consistent_act_on.py +++ b/cirq-core/cirq/testing/consistent_act_on.py @@ -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, cast, Optional, Type import numpy as np @@ -98,7 +95,7 @@ def assert_all_implemented_act_on_effects_match_unitary( "Could not assert if any act_on methods were " "implemented. Operating on qudits or with a " "non-unitary or parameterized operation is " - "unsupported.\n\nval: {!r}".format(val) + f"unsupported.\n\nval: {val!r}" ) return None @@ -127,7 +124,7 @@ def assert_all_implemented_act_on_effects_match_unitary( state_vector_has_stabilizer(state_vector, stab) for stab in tableau.stabilizers() ), ( "act_on clifford tableau is not consistent with " - "final_state_vector simulation.\n\nval: {!r}".format(val) + f"final_state_vector simulation.\n\nval: {val!r}" ) stabilizer_ch_form = _final_stabilizer_state_ch_form(circuit, qubit_map) @@ -136,7 +133,7 @@ def assert_all_implemented_act_on_effects_match_unitary( "Failed to generate final " "stabilizer state CH form " "for the test circuit." - "\n\nval: {!r}".format(val) + f"\n\nval: {val!r}" ) else: np.testing.assert_allclose( diff --git a/cirq-core/cirq/testing/consistent_protocols_test.py b/cirq-core/cirq/testing/consistent_protocols_test.py index 16d0de662ee..123e6a6b010 100644 --- a/cirq-core/cirq/testing/consistent_protocols_test.py +++ b/cirq-core/cirq/testing/consistent_protocols_test.py @@ -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 AbstractSet, Sequence, Union, List, Tuple import pytest @@ -189,8 +186,10 @@ def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: return [(0, np.diag([1, 0])), (1, np.diag([0, 1]))] def __repr__(self): - return 'GoodEigenGate(exponent={}, global_shift={!r})'.format( - proper_repr(self._exponent), self._global_shift + return ( + 'GoodEigenGate(' + f'exponent={proper_repr(self._exponent)}, ' + f'global_shift={self._global_shift!r})' ) @@ -199,8 +198,10 @@ def _eigen_shifts(self): return [0, 0] def __repr__(self): - return 'BadEigenGate(exponent={}, global_shift={!r})'.format( - proper_repr(self._exponent), self._global_shift + return ( + 'BadEigenGate(' + f'exponent={proper_repr(self._exponent)}, ' + f'global_shift={self._global_shift!r})' ) diff --git a/cirq-core/cirq/testing/consistent_qasm.py b/cirq-core/cirq/testing/consistent_qasm.py index 0cbaf4dc7be..a6a0608316d 100644 --- a/cirq-core/cirq/testing/consistent_qasm.py +++ b/cirq-core/cirq/testing/consistent_qasm.py @@ -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 warnings from typing import Any, List, Sequence, Optional @@ -94,21 +91,13 @@ def assert_qasm_is_consistent_with_unitary(val: Any): p_qasm_unitary = None raise AssertionError( 'QASM not consistent with cirq.unitary(op) up to global phase.\n\n' - 'op:\n{}\n\n' - 'cirq.unitary(op):\n{}\n\n' - 'Generated QASM:\n\n{}\n\n' - 'Unitary of generated QASM:\n{}\n\n' - 'Phased matched cirq.unitary(op):\n{}\n\n' - 'Phased matched unitary of generated QASM:\n{}\n\n' - 'Underlying error:\n{}'.format( - _indent(repr(op)), - _indent(repr(unitary)), - _indent(qasm), - _indent(repr(qasm_unitary)), - _indent(repr(p_unitary)), - _indent(repr(p_qasm_unitary)), - _indent(str(ex)), - ) + f'op:\n{_indent(repr(op))}\n\n' + f'cirq.unitary(op):\n{_indent(repr(unitary))}\n\n' + f'Generated QASM:\n\n{_indent(qasm)}\n\n' + f'Unitary of generated QASM:\n{_indent(repr(qasm_unitary))}\n\n' + f'Phased matched cirq.unitary(op):\n{_indent(repr(p_unitary))}\n\n' + f'Phased matched unitary of generated QASM:\n{_indent(repr(p_qasm_unitary))}\n\n' + f'Underlying error:\n{_indent(str(ex))}' ) diff --git a/cirq-core/cirq/testing/consistent_specified_has_unitary.py b/cirq-core/cirq/testing/consistent_specified_has_unitary.py index 53c57109129..0c3cf6d03f2 100644 --- a/cirq-core/cirq/testing/consistent_specified_has_unitary.py +++ b/cirq-core/cirq/testing/consistent_specified_has_unitary.py @@ -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 from cirq import protocols @@ -31,5 +28,5 @@ def assert_specifies_has_unitary_if_unitary(val: Any) -> None: "Value is unitary but doesn't specify a _has_unitary_ method that " "can be used to cheaply verify this fact.\n" "\n" - "val: {!r}".format(val) + f"val: {val!r}" ) diff --git a/cirq-core/cirq/testing/equivalent_repr_eval.py b/cirq-core/cirq/testing/equivalent_repr_eval.py index 46a1a59769f..56925da06c1 100644 --- a/cirq-core/cirq/testing/equivalent_repr_eval.py +++ b/cirq-core/cirq/testing/equivalent_repr_eval.py @@ -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, Dict, Optional @@ -55,10 +52,10 @@ def assert_equivalent_repr( raise AssertionError( 'eval(repr(value)) raised an exception.\n' '\n' - 'setup_code={}\n' - 'type(value): {}\n' - 'value={!r}\n' - 'error={!r}'.format(setup_code, type(value), value, ex) + f'setup_code={setup_code}\n' + f'type(value): {type(value)}\n' + f'value={value!r}\n' + f'error={ex!r}' ) assert eval_repr_value == value, ( @@ -90,14 +87,14 @@ def assert_equivalent_repr( a = eval(f'{value!r}.__class__', global_vals, local_vals) except Exception: raise AssertionError( - "The repr of a value of type {} wasn't 'dottable'.\n" - "{!r}.XXX must be equivalent to ({!r}).XXX, " - "but it raised an error instead.".format(type(value), value, value) + f"The repr of a value of type {type(value)} wasn't 'dottable'.\n" + f"{value!r}.XXX must be equivalent to ({value!r}).XXX, " + "but it raised an error instead." ) b = eval(f'({value!r}).__class__', global_vals, local_vals) assert a == b, ( - "The repr of a value of type {} wasn't 'dottable'.\n" - "{!r}.XXX must be equivalent to ({!r}).XXX, " - "but it wasn't.".format(type(value), value, value) + f"The repr of a value of type {type(value)} wasn't 'dottable'.\n" + f"{value!r}.XXX must be equivalent to ({value!r}).XXX, " + "but it wasn't." ) diff --git a/cirq-core/cirq/testing/order_tester.py b/cirq-core/cirq/testing/order_tester.py index a414bf5a6a6..1ecdc56dcc6 100644 --- a/cirq-core/cirq/testing/order_tester.py +++ b/cirq-core/cirq/testing/order_tester.py @@ -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 utility class for testing ordering methods. To test an ordering method, create an OrderTester and add several @@ -53,10 +50,9 @@ def _verify_ordering_one_sided(self, a: Any, b: Any, sign: int): expected = cmp_func(0, sign) actual = cmp_func(a, b) assert expected == actual, ( - "Ordering constraint violated. Expected X={} to {} Y={}, " - "but X {} Y returned {}".format( - a, ['be more than', 'equal', 'be less than'][sign + 1], b, cmp_name, actual - ) + f"Ordering constraint violated. Expected X={a} " + f"to {['be more than', 'equal', 'be less than'][sign + 1]} Y={b}, " + f"but X {cmp_name} Y returned {actual}" ) def _verify_ordering(self, a: Any, b: Any, sign: int): @@ -77,7 +73,7 @@ def _verify_not_implemented_vs_unknown(self, item: Any): " if not isinstance(other, type(self)):\n" " return NotImplemented\n" "\n" - "That rule is being violated by this value: {!r}".format(item) + f"That rule is being violated by this value: {item!r}" ) from ex def add_ascending(self, *items: Any): diff --git a/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition_test.py b/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition_test.py index fb4f6657b21..274203c5831 100644 --- a/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition_test.py +++ b/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition_test.py @@ -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 random import random from typing import Callable @@ -214,9 +211,7 @@ def test_middle_multiplexor(angles, num_cnots): ] ) == num_cnots - ), "expected {} CNOTs got \n {} \n {}".format( - num_cnots, circuit_u1u2_mid, circuit_u1u2_mid.unitary() - ) + ), f"expected {num_cnots} CNOTs got \n {circuit_u1u2_mid} \n {circuit_u1u2_mid.unitary()}" @pytest.mark.parametrize("shift_left", [True, False]) diff --git a/cirq-core/cirq/value/abc_alt.py b/cirq-core/cirq/value/abc_alt.py index af57df09353..6f631f20b31 100644 --- a/cirq-core/cirq/value/abc_alt.py +++ b/cirq-core/cirq/value/abc_alt.py @@ -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 more flexible abstract base class metaclass ABCMetaImplementAnyOneOf.""" import abc @@ -95,9 +92,9 @@ def has_some_implementation(name: str) -> bool: value = getattr(cls, name) except AttributeError: raise TypeError( - 'A method named \'{}\' was listed as a possible ' + f"A method named '{name}' was listed as a possible " 'implementation alternative but it does not exist in the ' - 'definition of {!r}.'.format(name, cls) + f'definition of {cls!r}.' ) if getattr(value, '__isabstractmethod__', False): return False diff --git a/cirq-core/cirq/value/digits.py b/cirq-core/cirq/value/digits.py index 24b13f93e81..19019a1bfc2 100644 --- a/cirq-core/cirq/value/digits.py +++ b/cirq-core/cirq/value/digits.py @@ -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 List, Iterable, Any, Union, Optional, overload @@ -185,8 +182,8 @@ def big_endian_int_to_digits( if val: raise ValueError( 'Out of range. ' - 'Extracted digits {!r} but the long division process ' - 'left behind {!r} instead of 0.'.format(result, val) + f'Extracted digits {result!r} but the long division process ' + f'left behind {val!r} instead of 0.' ) return result[::-1] diff --git a/cirq-core/cirq/value/linear_dict.py b/cirq-core/cirq/value/linear_dict.py index 1167711a404..ea886ab5d57 100644 --- a/cirq-core/cirq/value/linear_dict.py +++ b/cirq-core/cirq/value/linear_dict.py @@ -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 - """Linear combination represented as mapping of things to coefficients.""" import numbers from typing import ( @@ -45,8 +42,8 @@ def _format_coefficient(format_spec: str, coefficient: Scalar) -> str: coefficient = complex(coefficient) - real_str = '{:{fmt}}'.format(coefficient.real, fmt=format_spec) - imag_str = '{:{fmt}}'.format(coefficient.imag, fmt=format_spec) + real_str = f'{coefficient.real:{format_spec}}' + imag_str = f'{coefficient.imag:{format_spec}}' if float(real_str) == 0 and float(imag_str) == 0: return '' if float(imag_str) == 0: @@ -74,7 +71,7 @@ def _format_terms(terms: Iterable[Tuple[TVector, Scalar]], format_spec: str): formatted_terms = [_format_term(format_spec, vector, coeff) for vector, coeff in terms] s = ''.join(formatted_terms) if not s: - return '{:{fmt}}'.format(0, fmt=format_spec) + return f'{0:{format_spec}}' if s[0] == '+': return s[1:] return s diff --git a/cirq-core/cirq/value/product_state.py b/cirq-core/cirq/value/product_state.py index adf94da88a4..e7a76e2c1b7 100644 --- a/cirq-core/cirq/value/product_state.py +++ b/cirq-core/cirq/value/product_state.py @@ -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 abc from dataclasses import dataclass from typing import Dict, Iterator, Optional, Sequence, Tuple, TYPE_CHECKING @@ -81,7 +78,7 @@ def __mul__(self, other: 'cirq.ProductState') -> 'cirq.ProductState': if len(dupe_qubits) != 0: raise ValueError( "You tried to tensor two states, " - "but both contain factors for these qubits: {}".format(sorted(dupe_qubits)) + f"but both contain factors for these qubits: {sorted(dupe_qubits)}" ) new_states = self.states.copy() @@ -95,7 +92,7 @@ def __repr__(self) -> str: states_dict_repr = ', '.join( f'{repr(key)}: {repr(val)}' for key, val in self.states.items() ) - return 'cirq.ProductState({%s})' % states_dict_repr + return f'cirq.ProductState({{{states_dict_repr}}})' def __getitem__(self, qubit: 'cirq.Qid') -> _NamedOneQubitState: """Return the _NamedOneQubitState at the given qubit.""" diff --git a/cirq-core/cirq/work/observable_settings.py b/cirq-core/cirq/work/observable_settings.py index ad246beac82..6d68c3f7241 100644 --- a/cirq-core/cirq/work/observable_settings.py +++ b/cirq-core/cirq/work/observable_settings.py @@ -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 dataclasses import numbers from typing import ( @@ -58,7 +55,7 @@ def __post_init__(self): raise ValueError( "`observable`'s qubits should be a subset of those " "found in `init_state`. " - "observable qubits: {}. init_state qubits: {}".format(obs_qs, init_qs) + f"observable qubits: {obs_qs}. init_state qubits: {init_qs}" ) def __str__(self): diff --git a/cirq-google/cirq_google/api/v1/programs.py b/cirq-google/cirq_google/api/v1/programs.py index 2d1df05b814..c9448f1e4a3 100644 --- a/cirq-google/cirq_google/api/v1/programs.py +++ b/cirq-google/cirq_google/api/v1/programs.py @@ -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 json from typing import Any, cast, Dict, Optional, Sequence, Tuple, TYPE_CHECKING, Iterator import numpy as np @@ -335,7 +332,7 @@ def _parameterized_value_from_proto(proto: operations_pb2.ParameterizedFloat) -> raise ValueError( 'No value specified for parameterized float. ' 'Expected "raw" or "parameter_key" to be set. ' - 'proto: {!r}'.format(proto) + f'proto: {proto!r}' ) diff --git a/cirq-google/cirq_google/engine/calibration.py b/cirq-google/cirq_google/engine/calibration.py index 4fd58b02b87..d28434da6c0 100644 --- a/cirq-google/cirq_google/engine/calibration.py +++ b/cirq-google/cirq_google/engine/calibration.py @@ -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 - """Calibration wrapper for calibrations returned from the Quantum Engine.""" from collections import abc, defaultdict @@ -87,7 +84,7 @@ def _compute_metric_dict(self, metrics: v2.metrics_pb2.MetricsSnapshot) -> ALL_M else: assert len(results[name]) == 0, ( 'Only one metric of a given name can have no targets. ' - 'Found multiple for key {}'.format(name) + f'Found multiple for key {name}' ) results[name][()] = flat_values return results diff --git a/cirq-google/cirq_google/engine/engine_processor.py b/cirq-google/cirq_google/engine/engine_processor.py index 526ccd310f5..87db57adeef 100644 --- a/cirq-google/cirq_google/engine/engine_processor.py +++ b/cirq-google/cirq_google/engine/engine_processor.py @@ -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 datetime from typing import Dict, List, Optional, Sequence, TYPE_CHECKING, Union @@ -363,14 +360,14 @@ def list_calibrations( latest_timestamp_seconds = _date_to_timestamp(latest_timestamp) if earliest_timestamp_seconds and latest_timestamp_seconds: - filter_str = 'timestamp >= %d AND timestamp <= %d' % ( - earliest_timestamp_seconds, - latest_timestamp_seconds, + filter_str = ( + f'timestamp >= {earliest_timestamp_seconds:d} AND ' + f'timestamp <= {latest_timestamp_seconds:d}' ) elif earliest_timestamp_seconds: - filter_str = 'timestamp >= %d' % earliest_timestamp_seconds + filter_str = f'timestamp >= {earliest_timestamp_seconds:d}' elif latest_timestamp_seconds: - filter_str = 'timestamp <= %d' % latest_timestamp_seconds + filter_str = f'timestamp <= {latest_timestamp_seconds:d}' else: filter_str = '' response = self.context.client.list_calibrations( diff --git a/cirq-google/cirq_google/serialization/circuit_serializer.py b/cirq-google/cirq_google/serialization/circuit_serializer.py index 1895e85485a..73e1e53528b 100644 --- a/cirq-google/cirq_google/serialization/circuit_serializer.py +++ b/cirq-google/cirq_google/serialization/circuit_serializer.py @@ -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 - """Support for serializing and deserializing cirq_google.api.v2 protos.""" from typing import Any, Dict, List, Optional @@ -325,9 +322,7 @@ def deserialize(self, proto: v2.program_pb2.Program) -> cirq.Circuit: raise ValueError('Missing gate set specification.') if proto.language.gate_set != self.name: raise ValueError( - 'Gate set in proto was {} but expected {}'.format( - proto.language.gate_set, self.name - ) + f'Gate set in proto was {proto.language.gate_set} but expected {self.name}' ) which = proto.WhichOneof('program') arg_func_language = ( diff --git a/cirq-pasqal/cirq_pasqal/pasqal_device.py b/cirq-pasqal/cirq_pasqal/pasqal_device.py index 8b6d822f2bb..b68930a8768 100644 --- a/cirq-pasqal/cirq_pasqal/pasqal_device.py +++ b/cirq-pasqal/cirq_pasqal/pasqal_device.py @@ -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 Sequence, Any, Union, Dict import numpy as np import networkx as nx @@ -55,16 +52,15 @@ def __init__(self, qubits: Sequence[cirq.Qid]) -> None: for q in qubits: if not isinstance(q, self.supported_qubit_type): raise TypeError( - 'Unsupported qubit type: {!r}. This device ' - 'supports qubit types: {}'.format(q, self.supported_qubit_type) + f'Unsupported qubit type: {q!r}. This device ' + f'supports qubit types: {self.supported_qubit_type}' ) if not type(q) is q_type: raise TypeError("All qubits must be of same type.") if len(qubits) > self.maximum_qubit_number: raise ValueError( - 'Too many qubits. {} accepts at most {} ' - 'qubits.'.format(type(self), self.maximum_qubit_number) + f'Too many qubits. {type(self)} accepts at most {self.maximum_qubit_number} qubits.' ) self.gateset = PasqalGateset() @@ -115,9 +111,9 @@ def validate_operation(self, operation: cirq.Operation): for qub in operation.qubits: if not isinstance(qub, self.supported_qubit_type): raise ValueError( - '{} is not a valid qubit for gate {!r}. This ' - 'device accepts gates on qubits of type: ' - '{}'.format(qub, operation.gate, self.supported_qubit_type) + f'{qub} is not a valid qubit for gate {operation.gate!r}. This ' + f'device accepts gates on qubits of type: ' + f'{self.supported_qubit_type}' ) if qub not in self.metadata.qubit_set: raise ValueError(f'{qub} is not part of the device.') @@ -281,8 +277,10 @@ def distance(self, p: Any, q: Any) -> float: return np.sqrt((p.x - q.x) ** 2 + (p.y - q.y) ** 2 + (p.z - q.z) ** 2) def __repr__(self): - return ('pasqal.PasqalVirtualDevice(control_radius={!r}, qubits={!r})').format( - self.control_radius, sorted(self.qubits) + return ( + 'pasqal.PasqalVirtualDevice(' + f'control_radius={self.control_radius!r}, ' + f'qubits={sorted(self.qubits)!r})' ) def _value_equality_values_(self) -> Any: diff --git a/dev_tools/bash_scripts_test.py b/dev_tools/bash_scripts_test.py index 20d40ecfcd5..cc9e2dbb77d 100644 --- a/dev_tools/bash_scripts_test.py +++ b/dev_tools/bash_scripts_test.py @@ -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 os import subprocess from typing import Iterable @@ -59,23 +56,21 @@ def run( with open(file_path, 'w') as f: f.writelines(script_lines) - cmd = r""" + cmd = f""" export GIT_CONFIG_GLOBAL=/dev/null export GIT_CONFIG_SYSTEM=/dev/null dir=$(git rev-parse --show-toplevel) -cd {} +cd {dir_path} git init --quiet --initial-branch master git config --local user.name 'Me' git config --local user.email '<>' git commit -m init --allow-empty --quiet --no-gpg-sign -{} +{setup} mkdir -p dev_tools touch dev_tools/pypath chmod +x ./test-script.sh -./test-script.sh {} -""".format( - dir_path, setup, arg - ) +./test-script.sh {arg} +""" return shell_tools.run( cmd, log_run_to_stderr=False, shell=True, check=False, capture_output=True ) diff --git a/dev_tools/incremental_coverage.py b/dev_tools/incremental_coverage.py index 29da204aa21..dc7b833b046 100644 --- a/dev_tools/incremental_coverage.py +++ b/dev_tools/incremental_coverage.py @@ -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 Dict, Tuple, List, cast, Set, Optional import os.path @@ -310,6 +307,7 @@ def check_for_uncovered_lines(env: env_tools.PreparedEnv) -> int: ) ) for index, line, reason in uncovered_lines: + # pylint: disable=consider-using-f-string print( 'Line {} {} but not covered: {}'.format( shell_tools.highlight(str(index).rjust(4), color_code=shell_tools.BOLD), diff --git a/dev_tools/pr_monitor.py b/dev_tools/pr_monitor.py index 1bb94f723ae..79cff04edf7 100644 --- a/dev_tools/pr_monitor.py +++ b/dev_tools/pr_monitor.py @@ -1,6 +1,4 @@ # pylint: disable=wrong-or-nonexistent-copyright-notice - -# TODO(#6171): enable the check and fix pylint errors # pylint: disable=consider-using-f-string """Code to interact with GitHub API to label and auto-merge pull requests.""" @@ -177,7 +175,7 @@ def check_collaborator_has_write( Raises: RuntimeError: If the request does not return status 200 (success). """ - url = "https://api.github.com/repos/{}/{}/collaborators/{}/permission" "".format( + url = "https://api.github.com/repos/{}/{}/collaborators/{}/permission".format( repo.organization, repo.name, username ) diff --git a/dev_tools/prepared_env.py b/dev_tools/prepared_env.py index fd7572a1ace..3e929c9a2f7 100644 --- a/dev_tools/prepared_env.py +++ b/dev_tools/prepared_env.py @@ -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 sys from typing import List, Optional @@ -101,20 +98,17 @@ def report_status_to_github( if target_url is not None: payload['target_url'] = target_url - url = "https://api.github.com/repos/{}/{}/statuses/{}?access_token={}".format( - self.repository.organization, - self.repository.name, - self.actual_commit_id, - self.repository.access_token, + url = ( + f"https://api.github.com/repos/{self.repository.organization}/" + f"{self.repository.name}/statuses/{self.actual_commit_id}?" + f"access_token={self.repository.access_token}" ) response = requests.post(url, json=payload) if response.status_code != 201: raise IOError( - 'Request failed. Code: {}. Content: {!r}.'.format( - response.status_code, response.content - ) + f'Request failed. Code: {response.status_code}. Content: {response.content!r}.' ) def get_changed_files(self) -> List[str]: diff --git a/dev_tools/profiling/benchmark_simulators.py b/dev_tools/profiling/benchmark_simulators.py index 7d057388066..d8627b01a63 100644 --- a/dev_tools/profiling/benchmark_simulators.py +++ b/dev_tools/profiling/benchmark_simulators.py @@ -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 - """Tool to benchmarking simulators against a random circuit.""" import argparse @@ -75,9 +72,7 @@ def main( ): print('num_qubits,seconds per gate') for num_qubits in range(min_num_qubits, max_num_qubits + 1): - command = 'simulate(\'{}\', {}, {}, {})'.format( - sim_type, num_qubits, num_gates, run_repetitions - ) + command = f"simulate('{sim_type}', {num_qubits}, {num_gates}, {run_repetitions})" time = timeit.timeit(command, setup, number=num_repetitions) print(f'{num_qubits},{time / (num_repetitions * num_gates)}') diff --git a/dev_tools/snippets_test.py b/dev_tools/snippets_test.py index 02b269edd71..cc9e8955515 100644 --- a/dev_tools/snippets_test.py +++ b/dev_tools/snippets_test.py @@ -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 - """Tests for executable snippets in documentation. This tests runs code snippets that are executable in `.md` and `.rst` @@ -505,6 +502,7 @@ def print_capture(*values, sep=' '): assert_expected_lines_present_in_order(expected_outputs, output_lines) except AssertionError as ex: + # pylint: disable=consider-using-f-string new_msg = ex.args[0] + '\n\nIn snippet{}:\n{}'.format( "" if line_number is None else " (line {})".format(line_number), _indent([snippet]) ) @@ -518,6 +516,7 @@ def assert_code_snippet_fails(snippet: str, state: Dict, expected_failure_type: except Exception as ex: actual_failure_types = [e.__name__ for e in inspect.getmro(type(ex))] if expected_failure_type not in actual_failure_types: + # pylint: disable=consider-using-f-string raise AssertionError( 'Expected snippet to raise a {}, but it raised a {}.'.format( expected_failure_type, ' -> '.join(actual_failure_types) diff --git a/examples/bernstein_vazirani.py b/examples/bernstein_vazirani.py index ff6ebdc4319..e3f24c4cee8 100644 --- a/examples/bernstein_vazirani.py +++ b/examples/bernstein_vazirani.py @@ -1,8 +1,5 @@ # pylint: disable=wrong-or-nonexistent-copyright-notice -# TODO(#6171): enable the check and fix pylint errors -# pylint: disable=consider-using-f-string - """Demonstrates the Bernstein-Vazirani algorithm. The (non-recursive) Bernstein-Vazirani algorithm takes a black-box oracle @@ -60,9 +57,9 @@ def main(qubit_count=8): secret_factor_bits = [random.randint(0, 1) for _ in range(qubit_count)] oracle = make_oracle(input_qubits, output_qubit, secret_factor_bits, secret_bias_bit) print( - 'Secret function:\nf(a) = a·<{}> + {} (mod 2)'.format( - ', '.join(str(e) for e in secret_factor_bits), secret_bias_bit - ) + 'Secret function:\nf(a) = ' + f"a·<{', '.join(str(e) for e in secret_factor_bits)}> + " + f"{secret_bias_bit} (mod 2)" ) # Embed the oracle into a special quantum circuit querying it exactly once. @@ -79,9 +76,8 @@ def main(qubit_count=8): # Check if we actually found the secret value. most_common_bitstring = frequencies.most_common(1)[0][0] print( - 'Most common matches secret factors:\n{}'.format( - most_common_bitstring == bitstring(secret_factor_bits) - ) + 'Most common matches secret factors:\n' + f'{most_common_bitstring == bitstring(secret_factor_bits)}' ) diff --git a/examples/swap_networks.py b/examples/swap_networks.py index a6c7ba85f10..0749926d769 100644 --- a/examples/swap_networks.py +++ b/examples/swap_networks.py @@ -1,8 +1,5 @@ # pylint: disable=wrong-or-nonexistent-copyright-notice -# TODO(#6171): enable the check and fix pylint errors -# pylint: disable=consider-using-f-string - """Demonstrates swap networks. Swap networks are used to get around limited connectivity in a hardware device. @@ -153,9 +150,9 @@ def main(): vertices, edges, beta, gamma, use_logical_qubits, verbose ) print( - '1-round QAOA circuit (using {}s as logical indices):'.format( - 'qubit' if use_logical_qubits else 'integer' - ) + '1-round QAOA circuit (using ' + f"{'qubits' if use_logical_qubits else 'integers'} " + 'as logical indices):' ) print(circuit)