diff --git a/pyproject.toml b/pyproject.toml index 0740861c98c6..2f62557aa15b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -218,7 +218,6 @@ disable = [ # TODO(#9614): these were added in modern Pylint. Decide if we want to enable them. If so, # remove from here and fix the issues. Else, move it above this section and add a comment # with the rationale - "consider-using-f-string", "no-member", # for dynamically created members "not-context-manager", "unnecessary-lambda-assignment", # do not want to implement diff --git a/qiskit/assembler/assemble_circuits.py b/qiskit/assembler/assemble_circuits.py index b27fe47a02e6..a3d9b6bbb549 100644 --- a/qiskit/assembler/assemble_circuits.py +++ b/qiskit/assembler/assemble_circuits.py @@ -153,9 +153,9 @@ def _assemble_circuit( conditional_reg_idx = memory_slots + max_conditional_idx conversion_bfunc = QasmQobjInstruction( name="bfunc", - mask="0x%X" % mask, + mask="0x%X" % mask, # pylint: disable=consider-using-f-string relation="==", - val="0x%X" % val, + val="0x%X" % val, # pylint: disable=consider-using-f-string register=conditional_reg_idx, ) instructions.append(conversion_bfunc) diff --git a/qiskit/assembler/assemble_schedules.py b/qiskit/assembler/assemble_schedules.py index c60c28ff9a50..2d5ebefa2fd1 100644 --- a/qiskit/assembler/assemble_schedules.py +++ b/qiskit/assembler/assemble_schedules.py @@ -152,7 +152,7 @@ def _assemble_experiments( # TODO: add other experimental header items (see circuit assembler) qobj_experiment_header = qobj.QobjExperimentHeader( memory_slots=max_memory_slot + 1, # Memory slots are 0 indexed - name=sched.name or "Experiment-%d" % idx, + name=sched.name or f"Experiment-{idx}", metadata=metadata, ) @@ -306,18 +306,11 @@ def _validate_meas_map( common_next = next_inst_qubits.intersection(meas_set) if common_instr_qubits and common_next: raise QiskitError( - "Qubits {} and {} are in the same measurement grouping: {}. " + f"Qubits {common_instr_qubits} and {common_next} are in the same measurement " + f"grouping: {meas_map}. " "They must either be acquired at the same time, or disjointly" - ". Instead, they were acquired at times: {}-{} and " - "{}-{}".format( - common_instr_qubits, - common_next, - meas_map, - inst[0][0], - inst_end_time, - next_inst_time, - next_inst_time + next_inst[0][1], - ) + f". Instead, they were acquired at times: {inst[0][0]}-{inst_end_time} and " + f"{next_inst_time}-{next_inst_time + next_inst[0][1]}" ) diff --git a/qiskit/assembler/disassemble.py b/qiskit/assembler/disassemble.py index c94b108c4b25..127bbd35eb26 100644 --- a/qiskit/assembler/disassemble.py +++ b/qiskit/assembler/disassemble.py @@ -109,7 +109,7 @@ def _qobj_to_circuit_cals(qobj, pulse_lib): config = (tuple(gate["qubits"]), tuple(gate["params"])) cal = { config: pulse.Schedule( - name="{} {} {}".format(gate["name"], str(gate["params"]), str(gate["qubits"])) + name=f"{gate['name']} {str(gate['params'])} {str(gate['qubits'])}" ) } for instruction in gate["instructions"]: diff --git a/qiskit/circuit/classicalfunction/boolean_expression.py b/qiskit/circuit/classicalfunction/boolean_expression.py index 0f4a53494af4..e517f36db02b 100644 --- a/qiskit/circuit/classicalfunction/boolean_expression.py +++ b/qiskit/circuit/classicalfunction/boolean_expression.py @@ -116,7 +116,7 @@ def from_dimacs_file(cls, filename: str): expr_obj = cls.__new__(cls) if not isfile(filename): - raise FileNotFoundError("The file %s does not exists." % filename) + raise FileNotFoundError(f"The file {filename} does not exists.") expr_obj._tweedledum_bool_expression = BoolFunction.from_dimacs_file(filename) num_qubits = ( diff --git a/qiskit/circuit/classicalfunction/classical_function_visitor.py b/qiskit/circuit/classicalfunction/classical_function_visitor.py index dfe8b956b092..be89e8ee7f81 100644 --- a/qiskit/circuit/classicalfunction/classical_function_visitor.py +++ b/qiskit/circuit/classicalfunction/classical_function_visitor.py @@ -83,7 +83,7 @@ def bit_binop(self, op, values): """Uses ClassicalFunctionVisitor.bitops to extend self._network""" bitop = ClassicalFunctionVisitor.bitops.get(type(op)) if not bitop: - raise ClassicalFunctionParseError("Unknown binop.op %s" % op) + raise ClassicalFunctionParseError(f"Unknown binop.op {op}") binop = getattr(self._network, bitop) left_type, left_signal = values[0] @@ -112,19 +112,19 @@ def visit_UnaryOp(self, node): operand_type, operand_signal = self.visit(node.operand) if operand_type != "Int1": raise ClassicalFunctionCompilerTypeError( - "UntaryOp.op %s only support operation on Int1s for now" % node.op + f"UntaryOp.op {node.op} only support operation on Int1s for now" ) bitop = ClassicalFunctionVisitor.bitops.get(type(node.op)) if not bitop: raise ClassicalFunctionCompilerTypeError( - "UntaryOp.op %s does not operate with Int1 type " % node.op + f"UntaryOp.op {node.op} does not operate with Int1 type " ) return "Int1", getattr(self._network, bitop)(operand_signal) def visit_Name(self, node): """Reduce variable names.""" if node.id not in self.scopes[-1]: - raise ClassicalFunctionParseError("out of scope: %s" % node.id) + raise ClassicalFunctionParseError(f"out of scope: {node.id}") return self.scopes[-1][node.id] def generic_visit(self, node): @@ -143,7 +143,7 @@ def generic_visit(self, node): ), ): return super().generic_visit(node) - raise ClassicalFunctionParseError("Unknown node: %s" % type(node)) + raise ClassicalFunctionParseError(f"Unknown node: {type(node)}") def extend_scope(self, args_node: _ast.arguments) -> None: """Add the arguments to the scope""" diff --git a/qiskit/circuit/classicalfunction/utils.py b/qiskit/circuit/classicalfunction/utils.py index 237a8b838530..75dcd3e20a7a 100644 --- a/qiskit/circuit/classicalfunction/utils.py +++ b/qiskit/circuit/classicalfunction/utils.py @@ -47,7 +47,7 @@ def _convert_tweedledum_operator(op): if op.kind() == "py_operator": return op.py_op() else: - raise RuntimeError("Unrecognized operator: %s" % op.kind()) + raise RuntimeError(f"Unrecognized operator: {op.kind()}") # TODO: need to deal with cbits too! if op.num_controls() > 0: diff --git a/qiskit/circuit/classicalregister.py b/qiskit/circuit/classicalregister.py index 7a21e6b2fa58..802d8c602e2c 100644 --- a/qiskit/circuit/classicalregister.py +++ b/qiskit/circuit/classicalregister.py @@ -43,7 +43,7 @@ def __init__(self, register=None, index=None): super().__init__(register, index) else: raise CircuitError( - "Clbit needs a ClassicalRegister and %s was provided" % type(register).__name__ + f"Clbit needs a ClassicalRegister and {type(register).__name__} was provided" ) diff --git a/qiskit/circuit/delay.py b/qiskit/circuit/delay.py index a333125a5a2b..25e7a6f3356c 100644 --- a/qiskit/circuit/delay.py +++ b/qiskit/circuit/delay.py @@ -32,7 +32,7 @@ def __init__(self, duration, unit="dt"): unit: the unit of the duration. Must be ``"dt"`` or an SI-prefixed seconds unit. """ if unit not in {"s", "ms", "us", "ns", "ps", "dt"}: - raise CircuitError("Unknown unit %s is specified." % unit) + raise CircuitError(f"Unknown unit {unit} is specified.") super().__init__("delay", 1, 0, params=[duration], unit=unit) diff --git a/qiskit/circuit/duration.py b/qiskit/circuit/duration.py index 6acb230baadd..fdf6e99e6117 100644 --- a/qiskit/circuit/duration.py +++ b/qiskit/circuit/duration.py @@ -35,8 +35,8 @@ def duration_in_dt(duration_in_sec: float, dt_in_sec: float) -> int: rounding_error = abs(duration_in_sec - res * dt_in_sec) if rounding_error > 1e-15: warnings.warn( - "Duration is rounded to %d [dt] = %e [s] from %e [s]" - % (res, res * dt_in_sec, duration_in_sec), + f"Duration is rounded to {res:d} [dt] = {res * dt_in_sec:e} [s] " + f"from {duration_in_sec:e} [s]", UserWarning, ) return res diff --git a/qiskit/circuit/equivalence.py b/qiskit/circuit/equivalence.py index 45921c3f2293..17912517d244 100644 --- a/qiskit/circuit/equivalence.py +++ b/qiskit/circuit/equivalence.py @@ -249,7 +249,7 @@ def _build_basis_graph(self): ) node_map[decomp_basis] = decomp_basis_node - label = "{}\n{}".format(str(params), str(decomp) if num_qubits <= 5 else "...") + label = f"{str(params)}\n{str(decomp) if num_qubits <= 5 else '...'}" graph.add_edge( node_map[basis], node_map[decomp_basis], @@ -273,8 +273,8 @@ def _raise_if_param_mismatch(gate_params, circuit_parameters): if set(gate_parameters) != circuit_parameters: raise CircuitError( "Cannot add equivalence between circuit and gate " - "of different parameters. Gate params: {}. " - "Circuit params: {}.".format(gate_parameters, circuit_parameters) + f"of different parameters. Gate params: {gate_parameters}. " + f"Circuit params: {circuit_parameters}." ) @@ -282,10 +282,8 @@ def _raise_if_shape_mismatch(gate, circuit): if gate.num_qubits != circuit.num_qubits or gate.num_clbits != circuit.num_clbits: raise CircuitError( "Cannot add equivalence between circuit and gate " - "of different shapes. Gate: {} qubits and {} clbits. " - "Circuit: {} qubits and {} clbits.".format( - gate.num_qubits, gate.num_clbits, circuit.num_qubits, circuit.num_clbits - ) + f"of different shapes. Gate: {gate.num_qubits} qubits and {gate.num_clbits} clbits. " + f"Circuit: {circuit.num_qubits} qubits and {circuit.num_clbits} clbits." ) diff --git a/qiskit/circuit/gate.py b/qiskit/circuit/gate.py index 132526775860..d2c88f40bdb6 100644 --- a/qiskit/circuit/gate.py +++ b/qiskit/circuit/gate.py @@ -177,7 +177,7 @@ def _broadcast_3_or_more_args(qargs: list) -> Iterator[tuple[list, list]]: for arg in zip(*qargs): yield list(arg), [] else: - raise CircuitError("Not sure how to combine these qubit arguments:\n %s\n" % qargs) + raise CircuitError(f"Not sure how to combine these qubit arguments:\n {qargs}\n") def broadcast_arguments(self, qargs: list, cargs: list) -> Iterable[tuple[list, list]]: """Validation and handling of the arguments and its relationship. @@ -236,7 +236,7 @@ def broadcast_arguments(self, qargs: list, cargs: list) -> Iterable[tuple[list, elif len(qargs) >= 3: return Gate._broadcast_3_or_more_args(qargs) else: - raise CircuitError("This gate cannot handle %i arguments" % len(qargs)) + raise CircuitError(f"This gate cannot handle {len(qargs)} arguments") def validate_parameter(self, parameter): """Gate parameters should be int, float, or ParameterExpression""" diff --git a/qiskit/circuit/instruction.py b/qiskit/circuit/instruction.py index 44155783d409..f53c5b9e9b3c 100644 --- a/qiskit/circuit/instruction.py +++ b/qiskit/circuit/instruction.py @@ -81,7 +81,7 @@ def __init__(self, name, num_qubits, num_clbits, params, duration=None, unit="dt raise CircuitError("num_qubits and num_clbits must be integer.") if num_qubits < 0 or num_clbits < 0: raise CircuitError( - "bad instruction dimensions: %d qubits, %d clbits." % num_qubits, num_clbits + f"bad instruction dimensions: {num_qubits} qubits, {num_clbits} clbits." ) self._name = name self._num_qubits = num_qubits @@ -222,8 +222,9 @@ def __repr__(self) -> str: str: A representation of the Instruction instance with the name, number of qubits, classical bits and params( if any ) """ - return "Instruction(name='{}', num_qubits={}, num_clbits={}, params={})".format( - self.name, self.num_qubits, self.num_clbits, self.params + return ( + f"Instruction(name='{self.name}', num_qubits={self.num_qubits}, " + f"num_clbits={self.num_clbits}, params={self.params})" ) def soft_compare(self, other: "Instruction") -> bool: @@ -456,7 +457,7 @@ def inverse(self, annotated: bool = False): return AnnotatedOperation(self, InverseModifier()) if self.definition is None: - raise CircuitError("inverse() not implemented for %s." % self.name) + raise CircuitError(f"inverse() not implemented for {self.name}.") from qiskit.circuit import Gate # pylint: disable=cyclic-import diff --git a/qiskit/circuit/library/arithmetic/linear_pauli_rotations.py b/qiskit/circuit/library/arithmetic/linear_pauli_rotations.py index a40767154bc9..bc80ef778616 100644 --- a/qiskit/circuit/library/arithmetic/linear_pauli_rotations.py +++ b/qiskit/circuit/library/arithmetic/linear_pauli_rotations.py @@ -153,7 +153,7 @@ def _check_configuration(self, raise_on_failure: bool = True) -> bool: if raise_on_failure: raise CircuitError( "Not enough qubits in the circuit, need at least " - "{}.".format(self.num_state_qubits + 1) + f"{self.num_state_qubits + 1}." ) return valid diff --git a/qiskit/circuit/library/arithmetic/piecewise_chebyshev.py b/qiskit/circuit/library/arithmetic/piecewise_chebyshev.py index a27c57ef28fa..cc34d3631f59 100644 --- a/qiskit/circuit/library/arithmetic/piecewise_chebyshev.py +++ b/qiskit/circuit/library/arithmetic/piecewise_chebyshev.py @@ -122,7 +122,7 @@ def _check_configuration(self, raise_on_failure: bool = True) -> bool: if raise_on_failure: raise CircuitError( "Not enough qubits in the circuit, need at least " - "{}.".format(self.num_state_qubits + 1) + f"{self.num_state_qubits + 1}." ) return valid diff --git a/qiskit/circuit/library/arithmetic/piecewise_linear_pauli_rotations.py b/qiskit/circuit/library/arithmetic/piecewise_linear_pauli_rotations.py index 509433af5574..3d84e64ccb1b 100644 --- a/qiskit/circuit/library/arithmetic/piecewise_linear_pauli_rotations.py +++ b/qiskit/circuit/library/arithmetic/piecewise_linear_pauli_rotations.py @@ -202,7 +202,7 @@ def _check_configuration(self, raise_on_failure: bool = True) -> bool: if raise_on_failure: raise CircuitError( "Not enough qubits in the circuit, need at least " - "{}.".format(self.num_state_qubits + 1) + f"{self.num_state_qubits + 1}." ) if len(self.breakpoints) != len(self.slopes) or len(self.breakpoints) != len(self.offsets): diff --git a/qiskit/circuit/library/arithmetic/piecewise_polynomial_pauli_rotations.py b/qiskit/circuit/library/arithmetic/piecewise_polynomial_pauli_rotations.py index 7e79ed04da12..741b920e368d 100644 --- a/qiskit/circuit/library/arithmetic/piecewise_polynomial_pauli_rotations.py +++ b/qiskit/circuit/library/arithmetic/piecewise_polynomial_pauli_rotations.py @@ -237,7 +237,7 @@ def _check_configuration(self, raise_on_failure: bool = True) -> bool: if raise_on_failure: raise CircuitError( "Not enough qubits in the circuit, need at least " - "{}.".format(self.num_state_qubits + 1) + f"{self.num_state_qubits + 1}." ) if len(self.breakpoints) != len(self.coeffs) + 1: diff --git a/qiskit/circuit/library/arithmetic/polynomial_pauli_rotations.py b/qiskit/circuit/library/arithmetic/polynomial_pauli_rotations.py index 13fb82298819..4f04a04dd522 100644 --- a/qiskit/circuit/library/arithmetic/polynomial_pauli_rotations.py +++ b/qiskit/circuit/library/arithmetic/polynomial_pauli_rotations.py @@ -248,7 +248,7 @@ def _check_configuration(self, raise_on_failure: bool = True) -> bool: if raise_on_failure: raise CircuitError( "Not enough qubits in the circuit, need at least " - "{}.".format(self.num_state_qubits + 1) + f"{self.num_state_qubits + 1}." ) return valid diff --git a/qiskit/circuit/library/data_preparation/state_preparation.py b/qiskit/circuit/library/data_preparation/state_preparation.py index 43e80ead8836..1d9ad7f7b082 100644 --- a/qiskit/circuit/library/data_preparation/state_preparation.py +++ b/qiskit/circuit/library/data_preparation/state_preparation.py @@ -154,8 +154,8 @@ def _define_from_int(self): # Raise if number of bits is greater than num_qubits if len(intstr) > self.num_qubits: raise QiskitError( - "StatePreparation integer has %s bits, but this exceeds the" - " number of qubits in the circuit, %s." % (len(intstr), self.num_qubits) + f"StatePreparation integer has {len(intstr)} bits, but this exceeds the" + f" number of qubits in the circuit, {self.num_qubits}." ) for qubit, bit in enumerate(intstr): @@ -212,9 +212,9 @@ def broadcast_arguments(self, qargs, cargs): if self.num_qubits != len(flat_qargs): raise QiskitError( - "StatePreparation parameter vector has %d elements, therefore expects %s " - "qubits. However, %s were provided." - % (2**self.num_qubits, self.num_qubits, len(flat_qargs)) + f"StatePreparation parameter vector has {2**self.num_qubits}" + f" elements, therefore expects {self.num_qubits} " + f"qubits. However, {len(flat_qargs)} were provided." ) yield flat_qargs, [] @@ -226,8 +226,8 @@ def validate_parameter(self, parameter): if parameter in ["0", "1", "+", "-", "l", "r"]: return parameter raise CircuitError( - "invalid param label {} for instruction {}. Label should be " - "0, 1, +, -, l, or r ".format(type(parameter), self.name) + f"invalid param label {type(parameter)} for instruction {self.name}. Label should be " + "0, 1, +, -, l, or r " ) # StatePreparation instruction parameter can be int, float, and complex. diff --git a/qiskit/circuit/library/graph_state.py b/qiskit/circuit/library/graph_state.py index ceefff7971db..89d1edb035ff 100644 --- a/qiskit/circuit/library/graph_state.py +++ b/qiskit/circuit/library/graph_state.py @@ -74,7 +74,7 @@ def __init__(self, adjacency_matrix: list | np.ndarray) -> None: raise CircuitError("The adjacency matrix must be symmetric.") num_qubits = len(adjacency_matrix) - circuit = QuantumCircuit(num_qubits, name="graph: %s" % (adjacency_matrix)) + circuit = QuantumCircuit(num_qubits, name=f"graph: {adjacency_matrix}") circuit.h(range(num_qubits)) for i in range(num_qubits): diff --git a/qiskit/circuit/library/hamiltonian_gate.py b/qiskit/circuit/library/hamiltonian_gate.py index 2997d01ed487..d920d7873876 100644 --- a/qiskit/circuit/library/hamiltonian_gate.py +++ b/qiskit/circuit/library/hamiltonian_gate.py @@ -103,8 +103,7 @@ def __array__(self, dtype=None, copy=None): time = float(self.params[1]) except TypeError as ex: raise TypeError( - "Unable to generate Unitary matrix for " - "unbound t parameter {}".format(self.params[1]) + f"Unable to generate Unitary matrix for unbound t parameter {self.params[1]}" ) from ex arr = scipy.linalg.expm(-1j * self.params[0] * time) dtype = complex if dtype is None else dtype diff --git a/qiskit/circuit/library/hidden_linear_function.py b/qiskit/circuit/library/hidden_linear_function.py index 1140f1866f08..b68fda7f8fc5 100644 --- a/qiskit/circuit/library/hidden_linear_function.py +++ b/qiskit/circuit/library/hidden_linear_function.py @@ -82,7 +82,7 @@ def __init__(self, adjacency_matrix: Union[List[List[int]], np.ndarray]) -> None raise CircuitError("The adjacency matrix must be symmetric.") num_qubits = len(adjacency_matrix) - circuit = QuantumCircuit(num_qubits, name="hlf: %s" % adjacency_matrix) + circuit = QuantumCircuit(num_qubits, name=f"hlf: {adjacency_matrix}") circuit.h(range(num_qubits)) for i in range(num_qubits): diff --git a/qiskit/circuit/library/n_local/n_local.py b/qiskit/circuit/library/n_local/n_local.py index 430edfd94f39..25f6c27bbe1b 100644 --- a/qiskit/circuit/library/n_local/n_local.py +++ b/qiskit/circuit/library/n_local/n_local.py @@ -441,9 +441,8 @@ def ordered_parameters(self, parameters: ParameterVector | list[Parameter]) -> N ): raise ValueError( "The length of ordered parameters must be equal to the number of " - "settable parameters in the circuit ({}), but is {}".format( - self.num_parameters_settable, len(parameters) - ) + f"settable parameters in the circuit ({self.num_parameters_settable})," + f" but is {len(parameters)}" ) self._ordered_parameters = parameters self._invalidate() diff --git a/qiskit/circuit/library/n_local/qaoa_ansatz.py b/qiskit/circuit/library/n_local/qaoa_ansatz.py index d62e12c4d941..43869c0c54c9 100644 --- a/qiskit/circuit/library/n_local/qaoa_ansatz.py +++ b/qiskit/circuit/library/n_local/qaoa_ansatz.py @@ -97,20 +97,18 @@ def _check_configuration(self, raise_on_failure: bool = True) -> bool: valid = False if raise_on_failure: raise ValueError( - "The number of qubits of the initial state {} does not match " - "the number of qubits of the cost operator {}".format( - self.initial_state.num_qubits, self.num_qubits - ) + f"The number of qubits of the initial state {self.initial_state.num_qubits}" + " does not match " + f"the number of qubits of the cost operator {self.num_qubits}" ) if self.mixer_operator is not None and self.mixer_operator.num_qubits != self.num_qubits: valid = False if raise_on_failure: raise ValueError( - "The number of qubits of the mixer {} does not match " - "the number of qubits of the cost operator {}".format( - self.mixer_operator.num_qubits, self.num_qubits - ) + f"The number of qubits of the mixer {self.mixer_operator.num_qubits}" + f" does not match " + f"the number of qubits of the cost operator {self.num_qubits}" ) return valid diff --git a/qiskit/circuit/library/overlap.py b/qiskit/circuit/library/overlap.py index 2db6a80eedcc..f6ae5fd6ebdd 100644 --- a/qiskit/circuit/library/overlap.py +++ b/qiskit/circuit/library/overlap.py @@ -112,8 +112,6 @@ def _check_unitary(circuit): for instruction in circuit.data: if not isinstance(instruction.operation, (Gate, Barrier)): raise CircuitError( - ( - "One or more instructions cannot be converted to" - ' a gate. "{}" is not a gate instruction' - ).format(instruction.operation.name) + "One or more instructions cannot be converted to" + f' a gate. "{instruction.operation.name}" is not a gate instruction' ) diff --git a/qiskit/circuit/library/standard_gates/u3.py b/qiskit/circuit/library/standard_gates/u3.py index 62c1e33b9628..0eef2518a85a 100644 --- a/qiskit/circuit/library/standard_gates/u3.py +++ b/qiskit/circuit/library/standard_gates/u3.py @@ -344,7 +344,7 @@ def _generate_gray_code(num_bits): result = [0] for i in range(num_bits): result += [x + 2**i for x in reversed(result)] - return [format(x, "0%sb" % num_bits) for x in result] + return [format(x, f"0{num_bits}b") for x in result] def _gray_code_chain(q, num_ctrl_qubits, gate): diff --git a/qiskit/circuit/parameter.py b/qiskit/circuit/parameter.py index abe4e61adf63..825679f7d4f5 100644 --- a/qiskit/circuit/parameter.py +++ b/qiskit/circuit/parameter.py @@ -109,8 +109,8 @@ def subs(self, parameter_map: dict, allow_unknown_parameters: bool = False): if allow_unknown_parameters: return self raise CircuitError( - "Cannot bind Parameters ({}) not present in " - "expression.".format([str(p) for p in parameter_map]) + f"Cannot bind Parameters ({[str(p) for p in parameter_map]}) not present in " + "expression." ) @property diff --git a/qiskit/circuit/parameterexpression.py b/qiskit/circuit/parameterexpression.py index f881e09333d5..7f839677b904 100644 --- a/qiskit/circuit/parameterexpression.py +++ b/qiskit/circuit/parameterexpression.py @@ -140,7 +140,7 @@ def bind( raise ZeroDivisionError( "Binding provided for expression " "results in division by zero " - "(Expression: {}, Bindings: {}).".format(self, parameter_values) + f"(Expression: {self}, Bindings: {parameter_values})." ) return ParameterExpression(free_parameter_symbols, bound_symbol_expr) @@ -199,8 +199,8 @@ def _raise_if_passed_unknown_parameters(self, parameters): unknown_parameters = parameters - self.parameters if unknown_parameters: raise CircuitError( - "Cannot bind Parameters ({}) not present in " - "expression.".format([str(p) for p in unknown_parameters]) + f"Cannot bind Parameters ({[str(p) for p in unknown_parameters]}) not present in " + "expression." ) def _raise_if_passed_nan(self, parameter_values): @@ -404,8 +404,8 @@ def __complex__(self): except (TypeError, RuntimeError) as exc: if self.parameters: raise TypeError( - "ParameterExpression with unbound parameters ({}) " - "cannot be cast to a complex.".format(self.parameters) + f"ParameterExpression with unbound parameters ({self.parameters}) " + "cannot be cast to a complex." ) from None raise TypeError("could not cast expression to complex") from exc @@ -416,8 +416,8 @@ def __float__(self): except (TypeError, RuntimeError) as exc: if self.parameters: raise TypeError( - "ParameterExpression with unbound parameters ({}) " - "cannot be cast to a float.".format(self.parameters) + f"ParameterExpression with unbound parameters ({self.parameters}) " + "cannot be cast to a float." ) from None # In symengine, if an expression was complex at any time, its type is likely to have # stayed "complex" even when the imaginary part symbolically (i.e. exactly) @@ -436,8 +436,8 @@ def __int__(self): except RuntimeError as exc: if self.parameters: raise TypeError( - "ParameterExpression with unbound parameters ({}) " - "cannot be cast to an int.".format(self.parameters) + f"ParameterExpression with unbound parameters ({self.parameters}) " + "cannot be cast to an int." ) from None raise TypeError("could not cast expression to int") from exc diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py index e3fbf40da683..010a91e3639e 100644 --- a/qiskit/circuit/quantumcircuit.py +++ b/qiskit/circuit/quantumcircuit.py @@ -1067,8 +1067,9 @@ def __init__( if not valid_reg_size: raise CircuitError( - "Circuit args must be Registers or integers. (%s '%s' was " - "provided)" % ([type(reg).__name__ for reg in regs], regs) + "Circuit args must be Registers or integers. (" + f"{[type(reg).__name__ for reg in regs]} '{regs}' was " + "provided)" ) regs = tuple(int(reg) for reg in regs) # cast to int @@ -1659,7 +1660,7 @@ def power( raise CircuitError( "Cannot raise a parameterized circuit to a non-positive power " "or matrix-power, please bind the free parameters: " - "{}".format(self.parameters) + f"{self.parameters}" ) try: @@ -2957,14 +2958,14 @@ def add_register(self, *regs: Register | int | Sequence[Bit]) -> None: raise CircuitError( "QuantumCircuit parameters can be Registers or Integers." " If Integers, up to 2 arguments. QuantumCircuit was called" - " with %s." % (regs,) + f" with {(regs,)}." ) for register in regs: if isinstance(register, Register) and any( register.name == reg.name for reg in self.qregs + self.cregs ): - raise CircuitError('register name "%s" already exists' % register.name) + raise CircuitError(f'register name "{register.name}" already exists') if isinstance(register, AncillaRegister): for bit in register: @@ -3020,7 +3021,7 @@ def add_bits(self, bits: Iterable[Bit]) -> None: else: raise CircuitError( "Expected an instance of Qubit, Clbit, or " - "AncillaQubit, but was passed {}".format(bit) + f"AncillaQubit, but was passed {bit}" ) def find_bit(self, bit: Bit) -> BitLocations: diff --git a/qiskit/circuit/quantumregister.py b/qiskit/circuit/quantumregister.py index 2ae815b1d172..97d1392698e3 100644 --- a/qiskit/circuit/quantumregister.py +++ b/qiskit/circuit/quantumregister.py @@ -43,7 +43,7 @@ def __init__(self, register=None, index=None): super().__init__(register, index) else: raise CircuitError( - "Qubit needs a QuantumRegister and %s was provided" % type(register).__name__ + f"Qubit needs a QuantumRegister and {type(register).__name__} was provided" ) diff --git a/qiskit/circuit/register.py b/qiskit/circuit/register.py index e927d10e7360..39345705aaef 100644 --- a/qiskit/circuit/register.py +++ b/qiskit/circuit/register.py @@ -67,7 +67,7 @@ def __init__(self, size: int | None = None, name: str | None = None, bits=None): if (size, bits) == (None, None) or (size is not None and bits is not None): raise CircuitError( "Exactly one of the size or bits arguments can be " - "provided. Provided size=%s bits=%s." % (size, bits) + f"provided. Provided size={size} bits={bits}." ) # validate (or cast) size @@ -81,20 +81,18 @@ def __init__(self, size: int | None = None, name: str | None = None, bits=None): if not valid_size: raise CircuitError( - "Register size must be an integer. (%s '%s' was provided)" - % (type(size).__name__, size) + f"Register size must be an integer. ({type(size).__name__} '{size}' was provided)" ) size = int(size) # cast to int if size < 0: raise CircuitError( - "Register size must be non-negative (%s '%s' was provided)" - % (type(size).__name__, size) + f"Register size must be non-negative ({type(size).__name__} '{size}' was provided)" ) # validate (or cast) name if name is None: - name = "%s%i" % (self.prefix, next(self.instances_counter)) + name = f"{self.prefix}{next(self.instances_counter)}" else: try: name = str(name) @@ -108,7 +106,7 @@ def __init__(self, size: int | None = None, name: str | None = None, bits=None): self._size = size self._hash = hash((type(self), self._name, self._size)) - self._repr = "%s(%d, '%s')" % (self.__class__.__qualname__, self.size, self.name) + self._repr = f"{self.__class__.__qualname__}({self.size}, '{self.name}')" if bits is not None: # check duplicated bits if self._size != len(set(bits)): diff --git a/qiskit/circuit/tools/pi_check.py b/qiskit/circuit/tools/pi_check.py index d3614b747824..334b9683ae9b 100644 --- a/qiskit/circuit/tools/pi_check.py +++ b/qiskit/circuit/tools/pi_check.py @@ -104,9 +104,9 @@ def normalize(single_inpt): if power[0].shape[0]: if output == "qasm": if ndigits is None: - str_out = "{}".format(single_inpt) + str_out = str(single_inpt) else: - str_out = "{:.{}g}".format(single_inpt, ndigits) + str_out = f"{single_inpt:.{ndigits}g}" elif output == "latex": str_out = f"{neg_str}{pi}^{power[0][0] + 2}" elif output == "mpl": @@ -119,9 +119,9 @@ def normalize(single_inpt): # multiple or power of pi, since no fractions will exceed MAX_FRAC * pi if abs(single_inpt) >= (MAX_FRAC * np.pi): if ndigits is None: - str_out = "{}".format(single_inpt) + str_out = str(single_inpt) else: - str_out = "{:.{}g}".format(single_inpt, ndigits) + str_out = f"{single_inpt:.{ndigits}g}" return str_out # Fourth check is for fractions for 1*pi in the numer and any diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index a6c5212e2330..522e1c503ddf 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -34,7 +34,7 @@ def _log_assembly_time(start_time, end_time): - log_msg = "Total Assembly Time - %.5f (ms)" % ((end_time - start_time) * 1000) + log_msg = f"Total Assembly Time - {((end_time - start_time) * 1000):.5f} (ms)" logger.info(log_msg) @@ -311,8 +311,8 @@ def _parse_common_args( raise QiskitError("Argument 'shots' should be of type 'int'") elif max_shots and max_shots < shots: raise QiskitError( - "Number of shots specified: %s exceeds max_shots property of the " - "backend: %s." % (shots, max_shots) + f"Number of shots specified: {max_shots} exceeds max_shots property of the " + f"backend: {max_shots}." ) dynamic_reprate_enabled = getattr(backend_config, "dynamic_reprate_enabled", False) @@ -397,9 +397,8 @@ def _check_lo_freqs( raise QiskitError(f"Each element of {lo_type} LO range must be a 2d list.") if freq < freq_range[0] or freq > freq_range[1]: raise QiskitError( - "Qubit {} {} LO frequency is {}. The range is [{}, {}].".format( - i, lo_type, freq, freq_range[0], freq_range[1] - ) + f"Qubit {i} {lo_type} LO frequency is {freq}. " + f"The range is [{freq_range[0]}, {freq_range[1]}]." ) @@ -429,9 +428,8 @@ def _parse_pulse_args( if meas_level not in getattr(backend_config, "meas_levels", [MeasLevel.CLASSIFIED]): raise QiskitError( - ("meas_level = {} not supported for backend {}, only {} is supported").format( - meas_level, backend_config.backend_name, backend_config.meas_levels - ) + f"meas_level = {meas_level} not supported for backend " + f"{backend_config.backend_name}, only {backend_config.meas_levels} is supported" ) meas_map = meas_map or getattr(backend_config, "meas_map", None) @@ -522,14 +520,12 @@ def _parse_rep_delay( if rep_delay_range is not None and isinstance(rep_delay_range, list): if len(rep_delay_range) != 2: raise QiskitError( - "Backend rep_delay_range {} must be a list with two entries.".format( - rep_delay_range - ) + f"Backend rep_delay_range {rep_delay_range} must be a list with two entries." ) if not rep_delay_range[0] <= rep_delay <= rep_delay_range[1]: raise QiskitError( - "Supplied rep delay {} not in the supported " - "backend range {}".format(rep_delay, rep_delay_range) + f"Supplied rep delay {rep_delay} not in the supported " + f"backend range {rep_delay_range}" ) rep_delay = rep_delay * 1e6 # convert sec to μs diff --git a/qiskit/compiler/scheduler.py b/qiskit/compiler/scheduler.py index 0a30b07a49b1..f141902b7062 100644 --- a/qiskit/compiler/scheduler.py +++ b/qiskit/compiler/scheduler.py @@ -31,7 +31,7 @@ def _log_schedule_time(start_time, end_time): - log_msg = "Total Scheduling Time - %.5f (ms)" % ((end_time - start_time) * 1000) + log_msg = f"Total Scheduling Time - {((end_time - start_time) * 1000):.5f} (ms)" logger.info(log_msg) diff --git a/qiskit/compiler/transpiler.py b/qiskit/compiler/transpiler.py index 9dd316839a0f..183e260739ba 100644 --- a/qiskit/compiler/transpiler.py +++ b/qiskit/compiler/transpiler.py @@ -405,7 +405,7 @@ def _check_circuits_coupling_map(circuits, cmap, backend): def _log_transpile_time(start_time, end_time): - log_msg = "Total Transpile Time - %.5f (ms)" % ((end_time - start_time) * 1000) + log_msg = f"Total Transpile Time - {((end_time - start_time) * 1000):.5f} (ms)" logger.info(log_msg) @@ -476,7 +476,7 @@ def _parse_output_name(output_name, circuits): else: raise TranspilerError( "The parameter output_name should be a string or a" - "list of strings: %s was used." % type(output_name) + f"list of strings: {type(output_name)} was used." ) else: return [circuit.name for circuit in circuits] diff --git a/qiskit/converters/circuit_to_gate.py b/qiskit/converters/circuit_to_gate.py index 39eed1053eb1..c9f9ac6e1aff 100644 --- a/qiskit/converters/circuit_to_gate.py +++ b/qiskit/converters/circuit_to_gate.py @@ -64,10 +64,8 @@ def circuit_to_gate(circuit, parameter_map=None, equivalence_library=None, label for instruction in circuit.data: if not _check_is_gate(instruction.operation): raise QiskitError( - ( - "One or more instructions cannot be converted to" - ' a gate. "{}" is not a gate instruction' - ).format(instruction.operation.name) + "One or more instructions cannot be converted to" + f' a gate. "{instruction.operation.name}" is not a gate instruction' ) if parameter_map is None: @@ -77,10 +75,8 @@ def circuit_to_gate(circuit, parameter_map=None, equivalence_library=None, label if parameter_dict.keys() != circuit.parameters: raise QiskitError( - ( - "parameter_map should map all circuit parameters. " - "Circuit parameters: {}, parameter_map: {}" - ).format(circuit.parameters, parameter_dict) + "parameter_map should map all circuit parameters. " + f"Circuit parameters: {circuit.parameters}, parameter_map: {parameter_dict}" ) gate = Gate( diff --git a/qiskit/converters/circuit_to_instruction.py b/qiskit/converters/circuit_to_instruction.py index 1a5907c3ec84..571e330eb0db 100644 --- a/qiskit/converters/circuit_to_instruction.py +++ b/qiskit/converters/circuit_to_instruction.py @@ -89,10 +89,8 @@ def circuit_to_instruction(circuit, parameter_map=None, equivalence_library=None if parameter_dict.keys() != circuit.parameters: raise QiskitError( - ( - "parameter_map should map all circuit parameters. " - "Circuit parameters: {}, parameter_map: {}" - ).format(circuit.parameters, parameter_dict) + "parameter_map should map all circuit parameters. " + f"Circuit parameters: {circuit.parameters}, parameter_map: {parameter_dict}" ) out_instruction = Instruction( diff --git a/qiskit/dagcircuit/dagcircuit.py b/qiskit/dagcircuit/dagcircuit.py index 96562a37b151..686951f26fc2 100644 --- a/qiskit/dagcircuit/dagcircuit.py +++ b/qiskit/dagcircuit/dagcircuit.py @@ -271,7 +271,7 @@ def add_qubits(self, qubits): duplicate_qubits = set(self.qubits).intersection(qubits) if duplicate_qubits: - raise DAGCircuitError("duplicate qubits %s" % duplicate_qubits) + raise DAGCircuitError(f"duplicate qubits {duplicate_qubits}") for qubit in qubits: self.qubits.append(qubit) @@ -285,7 +285,7 @@ def add_clbits(self, clbits): duplicate_clbits = set(self.clbits).intersection(clbits) if duplicate_clbits: - raise DAGCircuitError("duplicate clbits %s" % duplicate_clbits) + raise DAGCircuitError(f"duplicate clbits {duplicate_clbits}") for clbit in clbits: self.clbits.append(clbit) @@ -297,7 +297,7 @@ def add_qreg(self, qreg): if not isinstance(qreg, QuantumRegister): raise DAGCircuitError("not a QuantumRegister instance.") if qreg.name in self.qregs: - raise DAGCircuitError("duplicate register %s" % qreg.name) + raise DAGCircuitError(f"duplicate register {qreg.name}") self.qregs[qreg.name] = qreg existing_qubits = set(self.qubits) for j in range(qreg.size): @@ -315,7 +315,7 @@ def add_creg(self, creg): if not isinstance(creg, ClassicalRegister): raise DAGCircuitError("not a ClassicalRegister instance.") if creg.name in self.cregs: - raise DAGCircuitError("duplicate register %s" % creg.name) + raise DAGCircuitError(f"duplicate register {creg.name}") self.cregs[creg.name] = creg existing_clbits = set(self.clbits) for j in range(creg.size): @@ -451,17 +451,17 @@ def remove_clbits(self, *clbits): """ if any(not isinstance(clbit, Clbit) for clbit in clbits): raise DAGCircuitError( - "clbits not of type Clbit: %s" % [b for b in clbits if not isinstance(b, Clbit)] + f"clbits not of type Clbit: {[b for b in clbits if not isinstance(b, Clbit)]}" ) clbits = set(clbits) unknown_clbits = clbits.difference(self.clbits) if unknown_clbits: - raise DAGCircuitError("clbits not in circuit: %s" % unknown_clbits) + raise DAGCircuitError(f"clbits not in circuit: {unknown_clbits}") busy_clbits = {bit for bit in clbits if not self._is_wire_idle(bit)} if busy_clbits: - raise DAGCircuitError("clbits not idle: %s" % busy_clbits) + raise DAGCircuitError(f"clbits not idle: {busy_clbits}") # remove any references to bits cregs_to_remove = {creg for creg in self.cregs.values() if not clbits.isdisjoint(creg)} @@ -487,13 +487,13 @@ def remove_cregs(self, *cregs): """ if any(not isinstance(creg, ClassicalRegister) for creg in cregs): raise DAGCircuitError( - "cregs not of type ClassicalRegister: %s" - % [r for r in cregs if not isinstance(r, ClassicalRegister)] + "cregs not of type ClassicalRegister: " + f"{[r for r in cregs if not isinstance(r, ClassicalRegister)]}" ) unknown_cregs = set(cregs).difference(self.cregs.values()) if unknown_cregs: - raise DAGCircuitError("cregs not in circuit: %s" % unknown_cregs) + raise DAGCircuitError(f"cregs not in circuit: {unknown_cregs}") for creg in cregs: del self.cregs[creg.name] @@ -517,17 +517,17 @@ def remove_qubits(self, *qubits): """ if any(not isinstance(qubit, Qubit) for qubit in qubits): raise DAGCircuitError( - "qubits not of type Qubit: %s" % [b for b in qubits if not isinstance(b, Qubit)] + f"qubits not of type Qubit: {[b for b in qubits if not isinstance(b, Qubit)]}" ) qubits = set(qubits) unknown_qubits = qubits.difference(self.qubits) if unknown_qubits: - raise DAGCircuitError("qubits not in circuit: %s" % unknown_qubits) + raise DAGCircuitError(f"qubits not in circuit: {unknown_qubits}") busy_qubits = {bit for bit in qubits if not self._is_wire_idle(bit)} if busy_qubits: - raise DAGCircuitError("qubits not idle: %s" % busy_qubits) + raise DAGCircuitError(f"qubits not idle: {busy_qubits}") # remove any references to bits qregs_to_remove = {qreg for qreg in self.qregs.values() if not qubits.isdisjoint(qreg)} @@ -553,13 +553,13 @@ def remove_qregs(self, *qregs): """ if any(not isinstance(qreg, QuantumRegister) for qreg in qregs): raise DAGCircuitError( - "qregs not of type QuantumRegister: %s" - % [r for r in qregs if not isinstance(r, QuantumRegister)] + f"qregs not of type QuantumRegister: " + f"{[r for r in qregs if not isinstance(r, QuantumRegister)]}" ) unknown_qregs = set(qregs).difference(self.qregs.values()) if unknown_qregs: - raise DAGCircuitError("qregs not in circuit: %s" % unknown_qregs) + raise DAGCircuitError(f"qregs not in circuit: {unknown_qregs}") for qreg in qregs: del self.qregs[qreg.name] @@ -581,13 +581,13 @@ def _is_wire_idle(self, wire): DAGCircuitError: the wire is not in the circuit. """ if wire not in self._wires: - raise DAGCircuitError("wire %s not in circuit" % wire) + raise DAGCircuitError(f"wire {wire} not in circuit") try: child = next(self.successors(self.input_map[wire])) except StopIteration as e: raise DAGCircuitError( - "Invalid dagcircuit input node %s has no output" % self.input_map[wire] + f"Invalid dagcircuit input node {self.input_map[wire]} has no output" ) from e return child is self.output_map[wire] @@ -950,12 +950,11 @@ def _reject_new_register(reg): # the mapped wire should already exist if m_wire not in dag.output_map: raise DAGCircuitError( - "wire %s[%d] not in self" % (m_wire.register.name, m_wire.index) + f"wire {m_wire.register.name}[{m_wire.index}] not in self" ) if nd.wire not in other._wires: raise DAGCircuitError( - "inconsistent wire type for %s[%d] in other" - % (nd.register.name, nd.wire.index) + f"inconsistent wire type for {nd.register.name}[{nd.wire.index}] in other" ) # If it's a Var wire, we already checked that it exists in the destination. elif isinstance(nd, DAGOutNode): @@ -974,7 +973,7 @@ def _reject_new_register(reg): op.target = variable_mapper.map_target(op.target) dag.apply_operation_back(op, m_qargs, m_cargs, check=False) else: - raise DAGCircuitError("bad node type %s" % type(nd)) + raise DAGCircuitError(f"bad node type {type(nd)}") if not inplace: return dag @@ -1632,10 +1631,10 @@ def substitute_node(self, node: DAGOpNode, op, inplace: bool = False, propagate_ if node.op.num_qubits != op.num_qubits or node.op.num_clbits != op.num_clbits: raise DAGCircuitError( - "Cannot replace node of width ({} qubits, {} clbits) with " - "operation of mismatched width ({} qubits, {} clbits).".format( - node.op.num_qubits, node.op.num_clbits, op.num_qubits, op.num_clbits - ) + f"Cannot replace node of width ({node.op.num_qubits} qubits, " + f"{node.op.num_clbits} clbits) with " + f"operation of mismatched width ({op.num_qubits} qubits, " + f"{op.num_clbits} clbits)." ) # This might include wires that are inherent to the node, like in its `condition` or @@ -1953,8 +1952,8 @@ def remove_op_node(self, node): """ if not isinstance(node, DAGOpNode): raise DAGCircuitError( - 'The method remove_op_node only works on DAGOpNodes. A "%s" ' - "node type was wrongly provided." % type(node) + f'The method remove_op_node only works on DAGOpNodes. A "{type(node)}" ' + "node type was wrongly provided." ) self._multi_graph.remove_node_retain_edges( @@ -2182,7 +2181,7 @@ def nodes_on_wire(self, wire, only_ops=False): current_node = self.input_map.get(wire, None) if not current_node: - raise DAGCircuitError("The given wire %s is not present in the circuit" % str(wire)) + raise DAGCircuitError(f"The given wire {str(wire)} is not present in the circuit") more_nodes = True while more_nodes: diff --git a/qiskit/dagcircuit/dagdependency.py b/qiskit/dagcircuit/dagdependency.py index 4316c9471401..63b91f920631 100644 --- a/qiskit/dagcircuit/dagdependency.py +++ b/qiskit/dagcircuit/dagdependency.py @@ -187,7 +187,7 @@ def add_qubits(self, qubits): duplicate_qubits = set(self.qubits).intersection(qubits) if duplicate_qubits: - raise DAGDependencyError("duplicate qubits %s" % duplicate_qubits) + raise DAGDependencyError(f"duplicate qubits {duplicate_qubits}") self.qubits.extend(qubits) @@ -198,7 +198,7 @@ def add_clbits(self, clbits): duplicate_clbits = set(self.clbits).intersection(clbits) if duplicate_clbits: - raise DAGDependencyError("duplicate clbits %s" % duplicate_clbits) + raise DAGDependencyError(f"duplicate clbits {duplicate_clbits}") self.clbits.extend(clbits) @@ -207,7 +207,7 @@ def add_qreg(self, qreg): if not isinstance(qreg, QuantumRegister): raise DAGDependencyError("not a QuantumRegister instance.") if qreg.name in self.qregs: - raise DAGDependencyError("duplicate register %s" % qreg.name) + raise DAGDependencyError(f"duplicate register {qreg.name}") self.qregs[qreg.name] = qreg existing_qubits = set(self.qubits) for j in range(qreg.size): @@ -219,7 +219,7 @@ def add_creg(self, creg): if not isinstance(creg, ClassicalRegister): raise DAGDependencyError("not a ClassicalRegister instance.") if creg.name in self.cregs: - raise DAGDependencyError("duplicate register %s" % creg.name) + raise DAGDependencyError(f"duplicate register {creg.name}") self.cregs[creg.name] = creg existing_clbits = set(self.clbits) for j in range(creg.size): diff --git a/qiskit/dagcircuit/dagdependency_v2.py b/qiskit/dagcircuit/dagdependency_v2.py index cb5d447162cb..e50c47b24f90 100644 --- a/qiskit/dagcircuit/dagdependency_v2.py +++ b/qiskit/dagcircuit/dagdependency_v2.py @@ -247,7 +247,7 @@ def add_qubits(self, qubits): duplicate_qubits = set(self.qubits).intersection(qubits) if duplicate_qubits: - raise DAGDependencyError("duplicate qubits %s" % duplicate_qubits) + raise DAGDependencyError(f"duplicate qubits {duplicate_qubits}") for qubit in qubits: self.qubits.append(qubit) @@ -260,7 +260,7 @@ def add_clbits(self, clbits): duplicate_clbits = set(self.clbits).intersection(clbits) if duplicate_clbits: - raise DAGDependencyError("duplicate clbits %s" % duplicate_clbits) + raise DAGDependencyError(f"duplicate clbits {duplicate_clbits}") for clbit in clbits: self.clbits.append(clbit) @@ -271,7 +271,7 @@ def add_qreg(self, qreg): if not isinstance(qreg, QuantumRegister): raise DAGDependencyError("not a QuantumRegister instance.") if qreg.name in self.qregs: - raise DAGDependencyError("duplicate register %s" % qreg.name) + raise DAGDependencyError(f"duplicate register {qreg.name}") self.qregs[qreg.name] = qreg existing_qubits = set(self.qubits) for j in range(qreg.size): @@ -288,7 +288,7 @@ def add_creg(self, creg): if not isinstance(creg, ClassicalRegister): raise DAGDependencyError("not a ClassicalRegister instance.") if creg.name in self.cregs: - raise DAGDependencyError("duplicate register %s" % creg.name) + raise DAGDependencyError(f"duplicate register {creg.name}") self.cregs[creg.name] = creg existing_clbits = set(self.clbits) for j in range(creg.size): diff --git a/qiskit/dagcircuit/dagdepnode.py b/qiskit/dagcircuit/dagdepnode.py index fe63f57d3d4f..cc00db9725c0 100644 --- a/qiskit/dagcircuit/dagdepnode.py +++ b/qiskit/dagcircuit/dagdepnode.py @@ -83,7 +83,7 @@ def __init__( def op(self): """Returns the Instruction object corresponding to the op for the node, else None""" if not self.type or self.type != "op": - raise QiskitError("The node %s is not an op node" % (str(self))) + raise QiskitError(f"The node {str(self)} is not an op node") return self._op @op.setter diff --git a/qiskit/passmanager/flow_controllers.py b/qiskit/passmanager/flow_controllers.py index c7d952d048dd..dcfcba704587 100644 --- a/qiskit/passmanager/flow_controllers.py +++ b/qiskit/passmanager/flow_controllers.py @@ -84,7 +84,7 @@ def iter_tasks(self, state: PassManagerState) -> Generator[Task, PassManagerStat return # Remove stored tasks from the completed task collection for next loop state.workflow_status.completed_passes.difference_update(self.tasks) - raise PassManagerError("Maximum iteration reached. max_iteration=%i" % max_iteration) + raise PassManagerError(f"Maximum iteration reached. max_iteration={max_iteration}") class ConditionalController(BaseController): diff --git a/qiskit/passmanager/passmanager.py b/qiskit/passmanager/passmanager.py index 8d3a4e9aa693..99527bf584ee 100644 --- a/qiskit/passmanager/passmanager.py +++ b/qiskit/passmanager/passmanager.py @@ -130,7 +130,7 @@ def __add__(self, other): return new_passmanager except PassManagerError as ex: raise TypeError( - "unsupported operand type + for %s and %s" % (self.__class__, other.__class__) + f"unsupported operand type + for {self.__class__} and {other.__class__}" ) from ex @abstractmethod diff --git a/qiskit/providers/backend.py b/qiskit/providers/backend.py index 2e551cc311e8..ed9fd3fdbb87 100644 --- a/qiskit/providers/backend.py +++ b/qiskit/providers/backend.py @@ -95,7 +95,7 @@ def __init__(self, configuration, provider=None, **fields): if fields: for field in fields: if field not in self._options.data: - raise AttributeError("Options field %s is not valid for this backend" % field) + raise AttributeError(f"Options field {field} is not valid for this backend") self._options.update_config(**fields) @classmethod @@ -129,7 +129,7 @@ def set_options(self, **fields): """ for field in fields: if not hasattr(self._options, field): - raise AttributeError("Options field %s is not valid for this backend" % field) + raise AttributeError(f"Options field {field} is not valid for this backend") self._options.update_options(**fields) def configuration(self): @@ -352,7 +352,7 @@ def __init__( if fields: for field in fields: if field not in self._options.data: - raise AttributeError("Options field %s is not valid for this backend" % field) + raise AttributeError(f"Options field {field} is not valid for this backend") self._options.update_config(**fields) self.name = name """Name of the backend.""" @@ -598,7 +598,7 @@ def set_options(self, **fields): """ for field in fields: if not hasattr(self._options, field): - raise AttributeError("Options field %s is not valid for this backend" % field) + raise AttributeError(f"Options field {field} is not valid for this backend") self._options.update_options(**fields) @property diff --git a/qiskit/providers/basic_provider/basic_provider_tools.py b/qiskit/providers/basic_provider/basic_provider_tools.py index b2670cc0977f..786815dda534 100644 --- a/qiskit/providers/basic_provider/basic_provider_tools.py +++ b/qiskit/providers/basic_provider/basic_provider_tools.py @@ -66,7 +66,7 @@ def single_gate_matrix(gate: str, params: list[float] | None = None) -> np.ndarr if gate in SINGLE_QUBIT_GATES: gc = SINGLE_QUBIT_GATES[gate] else: - raise QiskitError("Gate is not a valid basis gate for this simulator: %s" % gate) + raise QiskitError(f"Gate is not a valid basis gate for this simulator: {gate}") return gc(*params).to_matrix() diff --git a/qiskit/providers/basic_provider/basic_simulator.py b/qiskit/providers/basic_provider/basic_simulator.py index 978e1dad56fd..9971bf36725c 100644 --- a/qiskit/providers/basic_provider/basic_simulator.py +++ b/qiskit/providers/basic_provider/basic_simulator.py @@ -208,7 +208,7 @@ def _build_basic_target(self) -> Target: target.add_instruction(UnitaryGate, name="unitary") else: raise BasicProviderError( - "Gate is not a valid basis gate for this simulator: %s" % name + f"Gate is not a valid basis gate for this simulator: {name}" ) return target @@ -531,7 +531,7 @@ def run( for key, value in backend_options.items(): if not hasattr(self.options, key): warnings.warn( - "Option %s is not used by this backend" % key, UserWarning, stacklevel=2 + f"Option {key} is not used by this backend", UserWarning, stacklevel=2 ) else: out_options[key] = value diff --git a/qiskit/providers/fake_provider/fake_backend.py b/qiskit/providers/fake_provider/fake_backend.py index d84aba46371d..4a638f315574 100644 --- a/qiskit/providers/fake_provider/fake_backend.py +++ b/qiskit/providers/fake_provider/fake_backend.py @@ -143,8 +143,8 @@ def run(self, run_input, **kwargs): pulse_job = False if pulse_job is None: raise QiskitError( - "Invalid input object %s, must be either a " - "QuantumCircuit, Schedule, or a list of either" % circuits + f"Invalid input object {circuits}, must be either a " + "QuantumCircuit, Schedule, or a list of either" ) if pulse_job: raise QiskitError("Pulse simulation is currently not supported for fake backends.") diff --git a/qiskit/providers/fake_provider/generic_backend_v2.py b/qiskit/providers/fake_provider/generic_backend_v2.py index e806c75ea3a5..1ac0484d775d 100644 --- a/qiskit/providers/fake_provider/generic_backend_v2.py +++ b/qiskit/providers/fake_provider/generic_backend_v2.py @@ -496,8 +496,8 @@ def run(self, run_input, **options): pulse_job = False if pulse_job is None: # submitted job is invalid raise QiskitError( - "Invalid input object %s, must be either a " - "QuantumCircuit, Schedule, or a list of either" % circuits + f"Invalid input object {circuits}, must be either a " + "QuantumCircuit, Schedule, or a list of either" ) if pulse_job: # pulse job raise QiskitError("Pulse simulation is currently not supported for V2 backends.") diff --git a/qiskit/providers/models/backendproperties.py b/qiskit/providers/models/backendproperties.py index 3b5b9c5e010b..332aac7c5edd 100644 --- a/qiskit/providers/models/backendproperties.py +++ b/qiskit/providers/models/backendproperties.py @@ -404,9 +404,9 @@ def qubit_property( if name is not None: result = result[name] except KeyError as ex: + formatted_name = "y '" + name + "'" if name else "ies" raise BackendPropertyError( - "Couldn't find the propert{name} for qubit " - "{qubit}.".format(name="y '" + name + "'" if name else "ies", qubit=qubit) + f"Couldn't find the propert{formatted_name} for qubit {qubit}." ) from ex return result diff --git a/qiskit/providers/models/pulsedefaults.py b/qiskit/providers/models/pulsedefaults.py index 13becb1c956d..7c1864bad9ee 100644 --- a/qiskit/providers/models/pulsedefaults.py +++ b/qiskit/providers/models/pulsedefaults.py @@ -296,9 +296,4 @@ def __str__(self): meas_freqs = [freq / 1e9 for freq in self.meas_freq_est] qfreq = f"Qubit Frequencies [GHz]\n{qubit_freqs}" mfreq = f"Measurement Frequencies [GHz]\n{meas_freqs} " - return "<{name}({insts}{qfreq}\n{mfreq})>".format( - name=self.__class__.__name__, - insts=str(self.instruction_schedule_map), - qfreq=qfreq, - mfreq=mfreq, - ) + return f"<{self.__class__.__name__}({str(self.instruction_schedule_map)}{qfreq}\n{mfreq})>" diff --git a/qiskit/providers/options.py b/qiskit/providers/options.py index 8b2bffc52d84..fe4e7303a674 100644 --- a/qiskit/providers/options.py +++ b/qiskit/providers/options.py @@ -170,7 +170,7 @@ def __init__(self, **kwargs): def __repr__(self): items = (f"{k}={v!r}" for k, v in self._fields.items()) - return "{}({})".format(type(self).__name__, ", ".join(items)) + return f"{type(self).__name__}({', '.join(items)})" def __eq__(self, other): if isinstance(self, Options) and isinstance(other, Options): @@ -211,7 +211,7 @@ def set_validator(self, field, validator_value): """ if field not in self._fields: - raise KeyError("Field '%s' is not present in this options object" % field) + raise KeyError(f"Field '{field}' is not present in this options object") if isinstance(validator_value, tuple): if len(validator_value) != 2: raise ValueError( diff --git a/qiskit/pulse/configuration.py b/qiskit/pulse/configuration.py index 4668152973f2..1bfd1f13e2ee 100644 --- a/qiskit/pulse/configuration.py +++ b/qiskit/pulse/configuration.py @@ -55,11 +55,9 @@ def __init__(self, name: str | None = None, **params): self.params = params def __repr__(self): - return "{}({}{})".format( - self.__class__.__name__, - "'" + self.name + "', " or "", - ", ".join(f"{str(k)}={str(v)}" for k, v in self.params.items()), - ) + name_repr = "'" + self.name + "', " + params_repr = ", ".join(f"{str(k)}={str(v)}" for k, v in self.params.items()) + return f"{self.__class__.__name__}({name_repr}{params_repr})" def __eq__(self, other): if isinstance(other, Kernel): @@ -83,11 +81,9 @@ def __init__(self, name: str | None = None, **params): self.params = params def __repr__(self): - return "{}({}{})".format( - self.__class__.__name__, - "'" + self.name + "', " or "", - ", ".join(f"{str(k)}={str(v)}" for k, v in self.params.items()), - ) + name_repr = "'" + self.name + "', " or "" + params_repr = ", ".join(f"{str(k)}={str(v)}" for k, v in self.params.items()) + return f"{self.__class__.__name__}({name_repr}{params_repr})" def __eq__(self, other): if isinstance(other, Discriminator): @@ -184,7 +180,7 @@ def add_lo(self, channel: DriveChannel | MeasureChannel, freq: float): self.check_lo(channel, freq) self._m_lo_freq[channel] = freq else: - raise PulseError("Specified channel %s cannot be configured." % channel.name) + raise PulseError(f"Specified channel {channel.name} cannot be configured.") def add_lo_range( self, channel: DriveChannel | MeasureChannel, lo_range: LoRange | tuple[int, int] @@ -236,7 +232,7 @@ def channel_lo(self, channel: DriveChannel | MeasureChannel) -> float: if channel in self.meas_los: return self.meas_los[channel] - raise PulseError("Channel %s is not configured" % channel) + raise PulseError(f"Channel {channel} is not configured") @property def qubit_los(self) -> dict[DriveChannel, float]: diff --git a/qiskit/pulse/instruction_schedule_map.py b/qiskit/pulse/instruction_schedule_map.py index decda15c9947..afa71b6825a7 100644 --- a/qiskit/pulse/instruction_schedule_map.py +++ b/qiskit/pulse/instruction_schedule_map.py @@ -169,10 +169,8 @@ def assert_has( if not self.has(instruction, _to_tuple(qubits)): if instruction in self._map: raise PulseError( - "Operation '{inst}' exists, but is only defined for qubits " - "{qubits}.".format( - inst=instruction, qubits=self.qubits_with_instruction(instruction) - ) + f"Operation '{instruction}' exists, but is only defined for qubits " + f"{self.qubits_with_instruction(instruction)}." ) raise PulseError(f"Operation '{instruction}' is not defined for this system.") diff --git a/qiskit/pulse/instructions/acquire.py b/qiskit/pulse/instructions/acquire.py index 066163a79b0e..98fbf460c1b3 100644 --- a/qiskit/pulse/instructions/acquire.py +++ b/qiskit/pulse/instructions/acquire.py @@ -138,12 +138,11 @@ def is_parameterized(self) -> bool: return isinstance(self.duration, ParameterExpression) or super().is_parameterized() def __repr__(self) -> str: - return "{}({}{}{}{}{}{})".format( - self.__class__.__name__, - self.duration, - ", " + str(self.channel), - ", " + str(self.mem_slot) if self.mem_slot else "", - ", " + str(self.reg_slot) if self.reg_slot else "", - ", " + str(self.kernel) if self.kernel else "", - ", " + str(self.discriminator) if self.discriminator else "", + mem_slot_repr = str(self.mem_slot) if self.mem_slot else "" + reg_slot_repr = str(self.reg_slot) if self.reg_slot else "" + kernel_repr = str(self.kernel) if self.kernel else "" + discriminator_repr = str(self.discriminator) if self.discriminator else "" + return ( + f"{self.__class__.__name__}({self.duration}, {str(self.channel)}, " + f"{mem_slot_repr}, {reg_slot_repr}, {kernel_repr}, {discriminator_repr})" ) diff --git a/qiskit/pulse/instructions/instruction.py b/qiskit/pulse/instructions/instruction.py index ece20545b504..61ebe67777f8 100644 --- a/qiskit/pulse/instructions/instruction.py +++ b/qiskit/pulse/instructions/instruction.py @@ -264,6 +264,5 @@ def __lshift__(self, time: int): def __repr__(self) -> str: operands = ", ".join(str(op) for op in self.operands) - return "{}({}{})".format( - self.__class__.__name__, operands, f", name='{self.name}'" if self.name else "" - ) + name_repr = f", name='{self.name}'" if self.name else "" + return f"{self.__class__.__name__}({operands}{name_repr})" diff --git a/qiskit/pulse/library/samplers/decorators.py b/qiskit/pulse/library/samplers/decorators.py index ac78fba85954..db6aabd7b1de 100644 --- a/qiskit/pulse/library/samplers/decorators.py +++ b/qiskit/pulse/library/samplers/decorators.py @@ -182,9 +182,9 @@ def _update_docstring(discretized_pulse: Callable, sampler_inst: Callable) -> Ca header, body = wrapped_docstring.split("\n", 1) body = textwrap.indent(body, " ") wrapped_docstring = header + body - updated_ds = """ - Discretized continuous pulse function: `{continuous_name}` using - sampler: `{sampler_name}`. + updated_ds = f""" + Discretized continuous pulse function: `{discretized_pulse.__name__}` using + sampler: `{sampler_inst.__name__}`. The first argument (time) of the continuous pulse function has been replaced with a discretized `duration` of type (int). @@ -198,12 +198,8 @@ def _update_docstring(discretized_pulse: Callable, sampler_inst: Callable) -> Ca Sampled continuous function: - {continuous_doc} - """.format( - continuous_name=discretized_pulse.__name__, - sampler_name=sampler_inst.__name__, - continuous_doc=wrapped_docstring, - ) + {wrapped_docstring} + """ discretized_pulse.__doc__ = updated_ds return discretized_pulse diff --git a/qiskit/pulse/library/symbolic_pulses.py b/qiskit/pulse/library/symbolic_pulses.py index b076bcf56cb0..33d428771b22 100644 --- a/qiskit/pulse/library/symbolic_pulses.py +++ b/qiskit/pulse/library/symbolic_pulses.py @@ -570,11 +570,8 @@ def __eq__(self, other: object) -> bool: def __repr__(self) -> str: param_repr = ", ".join(f"{p}={v}" for p, v in self.parameters.items()) - return "{}({}{})".format( - self._pulse_type, - param_repr, - f", name='{self.name}'" if self.name is not None else "", - ) + name_repr = f", name='{self.name}'" if self.name is not None else "" + return f"{self._pulse_type}({param_repr}{name_repr})" __hash__ = None diff --git a/qiskit/pulse/library/waveform.py b/qiskit/pulse/library/waveform.py index e9ad9bcbc717..ad852f226ac2 100644 --- a/qiskit/pulse/library/waveform.py +++ b/qiskit/pulse/library/waveform.py @@ -130,8 +130,5 @@ def __repr__(self) -> str: opt = np.get_printoptions() np.set_printoptions(threshold=50) np.set_printoptions(**opt) - return "{}({}{})".format( - self.__class__.__name__, - repr(self.samples), - f", name='{self.name}'" if self.name is not None else "", - ) + name_repr = f", name='{self.name}'" if self.name is not None else "" + return f"{self.__class__.__name__}({repr(self.samples)}{name_repr})" diff --git a/qiskit/pulse/macros.py b/qiskit/pulse/macros.py index 88414cfc7e9b..3a39932e5b10 100644 --- a/qiskit/pulse/macros.py +++ b/qiskit/pulse/macros.py @@ -135,10 +135,10 @@ def _measure_v1( default_sched = inst_map.get(measure_name, measure_group_qubits) except exceptions.PulseError as ex: raise exceptions.PulseError( - "We could not find a default measurement schedule called '{}'. " + f"We could not find a default measurement schedule called '{measure_name}'. " "Please provide another name using the 'measure_name' keyword " "argument. For assistance, the instructions which are defined are: " - "{}".format(measure_name, inst_map.instructions) + f"{inst_map.instructions}" ) from ex for time, inst in default_sched.instructions: if inst.channel.index not in qubits: @@ -203,10 +203,10 @@ def _measure_v2( schedule += _schedule_remapping_memory_slot(default_sched, qubit_mem_slots) except KeyError as ex: raise exceptions.PulseError( - "We could not find a default measurement schedule called '{}'. " + f"We could not find a default measurement schedule called '{measure_name}'. " "Please provide another name using the 'measure_name' keyword " "argument. For assistance, the instructions which are defined are: " - "{}".format(measure_name, target.instructions) + f"{target.instructions}" ) from ex return schedule diff --git a/qiskit/pulse/parser.py b/qiskit/pulse/parser.py index 8e31faebf77a..e9cd4917a7ce 100644 --- a/qiskit/pulse/parser.py +++ b/qiskit/pulse/parser.py @@ -124,13 +124,11 @@ def __call__(self, *args, **kwargs) -> complex | ast.Expression | PulseExpressio self._locals_dict[key] = val else: raise PulseError( - "%s got multiple values for argument '%s'" - % (self.__class__.__name__, key) + f"{self.__class__.__name__} got multiple values for argument '{key}'" ) else: raise PulseError( - "%s got an unexpected keyword argument '%s'" - % (self.__class__.__name__, key) + f"{self.__class__.__name__} got an unexpected keyword argument '{key}'" ) expr = self.visit(self._tree) @@ -139,7 +137,7 @@ def __call__(self, *args, **kwargs) -> complex | ast.Expression | PulseExpressio if self._partial_binding: return PulseExpression(expr, self._partial_binding) else: - raise PulseError("Parameters %s are not all bound." % self.params) + raise PulseError(f"Parameters {self.params} are not all bound.") return expr.body.value @staticmethod @@ -160,7 +158,7 @@ def _match_ops(opr: ast.AST, opr_dict: dict, *args) -> complex: for op_type, op_func in opr_dict.items(): if isinstance(opr, op_type): return op_func(*args) - raise PulseError("Operator %s is not supported." % opr.__class__.__name__) + raise PulseError(f"Operator {opr.__class__.__name__} is not supported.") def visit_Expression(self, node: ast.Expression) -> ast.Expression: """Evaluate children nodes of expression. @@ -273,7 +271,7 @@ def visit_Call(self, node: ast.Call) -> ast.Call | ast.Constant: node.args = [self.visit(arg) for arg in node.args] if all(isinstance(arg, ast.Constant) for arg in node.args): if node.func.id not in self._math_ops: - raise PulseError("Function %s is not supported." % node.func.id) + raise PulseError(f"Function {node.func.id} is not supported.") _args = [arg.value for arg in node.args] _val = self._math_ops[node.func.id](*_args) if not _val.imag: @@ -283,7 +281,7 @@ def visit_Call(self, node: ast.Call) -> ast.Call | ast.Constant: return node def generic_visit(self, node): - raise PulseError("Unsupported node: %s" % node.__class__.__name__) + raise PulseError(f"Unsupported node: {node.__class__.__name__}") def parse_string_expr(source: str, partial_binding: bool = False) -> PulseExpression: diff --git a/qiskit/pulse/schedule.py b/qiskit/pulse/schedule.py index 5241da0c31d1..7ccd5053e6e0 100644 --- a/qiskit/pulse/schedule.py +++ b/qiskit/pulse/schedule.py @@ -553,17 +553,10 @@ def _add_timeslots(self, time: int, schedule: "ScheduleComponent") -> None: self._timeslots[channel].insert(index, interval) except PulseError as ex: raise PulseError( - "Schedule(name='{new}') cannot be inserted into Schedule(name='{old}') at " - "time {time} because its instruction on channel {ch} scheduled from time " - "{t0} to {tf} overlaps with an existing instruction." - "".format( - new=schedule.name or "", - old=self.name or "", - time=time, - ch=channel, - t0=interval[0], - tf=interval[1], - ) + f"Schedule(name='{schedule.name or ''}') cannot be inserted into " + f"Schedule(name='{self.name or ''}') at " + f"time {time} because its instruction on channel {channel} scheduled from time " + f"{interval[0]} to {interval[1]} overlaps with an existing instruction." ) from ex _check_nonnegative_timeslot(self._timeslots) @@ -598,10 +591,8 @@ def _remove_timeslots(self, time: int, schedule: "ScheduleComponent"): continue raise PulseError( - "Cannot find interval ({t0}, {tf}) to remove from " - "channel {ch} in Schedule(name='{name}').".format( - ch=channel, t0=interval[0], tf=interval[1], name=schedule.name - ) + f"Cannot find interval ({interval[0]}, {interval[1]}) to remove from " + f"channel {channel} in Schedule(name='{schedule.name}')." ) if not channel_timeslots: @@ -1615,8 +1606,9 @@ def __repr__(self) -> str: blocks = ", ".join([repr(instr) for instr in self.blocks[:50]]) if len(self.blocks) > 25: blocks += ", ..." - return '{}({}, name="{}", transform={})'.format( - self.__class__.__name__, blocks, name, repr(self.alignment_context) + return ( + f'{self.__class__.__name__}({blocks}, name="{name}",' + f" transform={repr(self.alignment_context)})" ) def __add__(self, other: "BlockComponent") -> "ScheduleBlock": diff --git a/qiskit/pulse/transforms/alignments.py b/qiskit/pulse/transforms/alignments.py index 569219777f20..5e383972c255 100644 --- a/qiskit/pulse/transforms/alignments.py +++ b/qiskit/pulse/transforms/alignments.py @@ -398,9 +398,7 @@ def align(self, schedule: Schedule) -> Schedule: _t_center = self.duration * self.func(ind + 1) _t0 = int(_t_center - 0.5 * child.duration) if _t0 < 0 or _t0 > self.duration: - raise PulseError( - "Invalid schedule position t=%d is specified at index=%d" % (_t0, ind) - ) + raise PulseError(f"Invalid schedule position t={_t0} is specified at index={ind}") aligned.insert(_t0, child, inplace=True) return aligned diff --git a/qiskit/pulse/utils.py b/qiskit/pulse/utils.py index ae87fbafadde..5f345917761e 100644 --- a/qiskit/pulse/utils.py +++ b/qiskit/pulse/utils.py @@ -108,10 +108,9 @@ def instruction_duration_validation(duration: int): """ if isinstance(duration, ParameterExpression): raise UnassignedDurationError( - "Instruction duration {} is not assigned. " + f"Instruction duration {repr(duration)} is not assigned. " "Please bind all durations to an integer value before playing in the Schedule, " "or use ScheduleBlock to align instructions with unassigned duration." - "".format(repr(duration)) ) if not isinstance(duration, (int, np.integer)) or duration < 0: diff --git a/qiskit/qasm2/export.py b/qiskit/qasm2/export.py index 9247c9233e09..46471fa087b2 100644 --- a/qiskit/qasm2/export.py +++ b/qiskit/qasm2/export.py @@ -157,7 +157,7 @@ def dumps(circuit: QuantumCircuit, /) -> str: _make_unique(_escape_name(reg.name, "reg_"), register_escaped_names) ] = reg bit_labels: dict[Qubit | Clbit, str] = { - bit: "%s[%d]" % (name, idx) + bit: f"{name}[{idx}]" for name, register in register_escaped_names.items() for (idx, bit) in enumerate(register) } @@ -244,18 +244,14 @@ def _instruction_call_site(operation): else: qasm2_call = operation.name if operation.params: - qasm2_call = "{}({})".format( - qasm2_call, - ",".join([pi_check(i, output="qasm", eps=1e-12) for i in operation.params]), - ) + params = ",".join([pi_check(i, output="qasm", eps=1e-12) for i in operation.params]) + qasm2_call = f"{qasm2_call}({params})" if operation.condition is not None: if not isinstance(operation.condition[0], ClassicalRegister): raise QASM2ExportError( "OpenQASM 2 can only condition on registers, but got '{operation.condition[0]}'" ) - qasm2_call = ( - "if(%s==%d) " % (operation.condition[0].name, operation.condition[1]) + qasm2_call - ) + qasm2_call = f"if({operation.condition[0].name}=={operation.condition[1]:d}) " + qasm2_call return qasm2_call diff --git a/qiskit/qobj/converters/pulse_instruction.py b/qiskit/qobj/converters/pulse_instruction.py index 80c332aaab4a..11374e9aca92 100644 --- a/qiskit/qobj/converters/pulse_instruction.py +++ b/qiskit/qobj/converters/pulse_instruction.py @@ -621,7 +621,7 @@ def get_channel(self, channel: str) -> channels.PulseChannel: elif prefix == channels.ControlChannel.prefix: return channels.ControlChannel(index) - raise QiskitError("Channel %s is not valid" % channel) + raise QiskitError(f"Channel {channel} is not valid") @staticmethod def disassemble_value(value_expr: Union[float, str]) -> Union[float, ParameterExpression]: @@ -827,9 +827,7 @@ def _convert_parametric_pulse( pulse_name = instruction.label except AttributeError: sorted_params = sorted(instruction.parameters.items(), key=lambda x: x[0]) - base_str = "{pulse}_{params}".format( - pulse=instruction.pulse_shape, params=str(sorted_params) - ) + base_str = f"{instruction.pulse_shape}_{str(sorted_params)}" short_pulse_id = hashlib.md5(base_str.encode("utf-8")).hexdigest()[:4] pulse_name = f"{instruction.pulse_shape}_{short_pulse_id}" params = dict(instruction.parameters) diff --git a/qiskit/qobj/pulse_qobj.py b/qiskit/qobj/pulse_qobj.py index e5f45b4d2acb..3552d83ada84 100644 --- a/qiskit/qobj/pulse_qobj.py +++ b/qiskit/qobj/pulse_qobj.py @@ -209,8 +209,8 @@ def __repr__(self): return out def __str__(self): - out = "Instruction: %s\n" % self.name - out += "\t\tt0: %s\n" % self.t0 + out = f"Instruction: {self.name}\n" + out += f"\t\tt0: {self.t0}\n" for attr in self._COMMON_ATTRS: if hasattr(self, attr): out += f"\t\t{attr}: {getattr(self, attr)}\n" @@ -434,10 +434,10 @@ def __str__(self): header = pprint.pformat(self.header.to_dict() or {}) else: header = "{}" - out += "Header:\n%s\n" % header - out += "Config:\n%s\n\n" % config + out += f"Header:\n{header}\n" + out += f"Config:\n{config}\n\n" for instruction in self.instructions: - out += "\t%s\n" % instruction + out += f"\t{instruction}\n" return out @classmethod @@ -567,23 +567,20 @@ def __init__(self, qobj_id, config, experiments, header=None): def __repr__(self): experiments_str = [repr(x) for x in self.experiments] experiments_repr = "[" + ", ".join(experiments_str) + "]" - out = "PulseQobj(qobj_id='{}', config={}, experiments={}, header={})".format( - self.qobj_id, - repr(self.config), - experiments_repr, - repr(self.header), + return ( + f"PulseQobj(qobj_id='{self.qobj_id}', config={repr(self.config)}, " + f"experiments={experiments_repr}, header={repr(self.header)})" ) - return out def __str__(self): - out = "Pulse Qobj: %s:\n" % self.qobj_id + out = f"Pulse Qobj: {self.qobj_id}:\n" config = pprint.pformat(self.config.to_dict()) - out += "Config: %s\n" % str(config) + out += f"Config: {str(config)}\n" header = pprint.pformat(self.header.to_dict()) - out += "Header: %s\n" % str(header) + out += f"Header: {str(header)}\n" out += "Experiments:\n" for experiment in self.experiments: - out += "%s" % str(experiment) + out += str(experiment) return out def to_dict(self): diff --git a/qiskit/qobj/qasm_qobj.py b/qiskit/qobj/qasm_qobj.py index 983da1dcfd3b..88d775b3b773 100644 --- a/qiskit/qobj/qasm_qobj.py +++ b/qiskit/qobj/qasm_qobj.py @@ -131,7 +131,7 @@ def to_dict(self): return out_dict def __repr__(self): - out = "QasmQobjInstruction(name='%s'" % self.name + out = f"QasmQobjInstruction(name='{self.name}'" for attr in [ "params", "qubits", @@ -155,7 +155,7 @@ def __repr__(self): return out def __str__(self): - out = "Instruction: %s\n" % self.name + out = f"Instruction: {self.name}\n" for attr in [ "params", "qubits", @@ -215,21 +215,19 @@ def __init__(self, config=None, header=None, instructions=None): def __repr__(self): instructions_str = [repr(x) for x in self.instructions] instructions_repr = "[" + ", ".join(instructions_str) + "]" - out = "QasmQobjExperiment(config={}, header={}, instructions={})".format( - repr(self.config), - repr(self.header), - instructions_repr, + return ( + f"QasmQobjExperiment(config={repr(self.config)}, header={repr(self.header)}," + f" instructions={instructions_repr})" ) - return out def __str__(self): out = "\nOpenQASM2 Experiment:\n" config = pprint.pformat(self.config.to_dict()) header = pprint.pformat(self.header.to_dict()) - out += "Header:\n%s\n" % header - out += "Config:\n%s\n\n" % config + out += f"Header:\n{header}\n" + out += f"Config:\n{config}\n\n" for instruction in self.instructions: - out += "\t%s\n" % instruction + out += f"\t{instruction}\n" return out def to_dict(self): @@ -568,23 +566,20 @@ def __init__(self, qobj_id=None, config=None, experiments=None, header=None): def __repr__(self): experiments_str = [repr(x) for x in self.experiments] experiments_repr = "[" + ", ".join(experiments_str) + "]" - out = "QasmQobj(qobj_id='{}', config={}, experiments={}, header={})".format( - self.qobj_id, - repr(self.config), - experiments_repr, - repr(self.header), + return ( + f"QasmQobj(qobj_id='{self.qobj_id}', config={repr(self.config)}," + f" experiments={experiments_repr}, header={repr(self.header)})" ) - return out def __str__(self): - out = "QASM Qobj: %s:\n" % self.qobj_id + out = f"QASM Qobj: {self.qobj_id}:\n" config = pprint.pformat(self.config.to_dict()) - out += "Config: %s\n" % str(config) + out += f"Config: {str(config)}\n" header = pprint.pformat(self.header.to_dict()) - out += "Header: %s\n" % str(header) + out += f"Header: {str(header)}\n" out += "Experiments:\n" for experiment in self.experiments: - out += "%s" % str(experiment) + out += str(experiment) return out def to_dict(self): diff --git a/qiskit/qpy/binary_io/circuits.py b/qiskit/qpy/binary_io/circuits.py index db53defbcfa7..0e2045d5be5d 100644 --- a/qiskit/qpy/binary_io/circuits.py +++ b/qiskit/qpy/binary_io/circuits.py @@ -128,7 +128,7 @@ def _read_registers_v4(file_obj, num_registers): ) ) name = file_obj.read(data.name_size).decode("utf8") - REGISTER_ARRAY_PACK = "!%sq" % data.size + REGISTER_ARRAY_PACK = f"!{data.size}q" bit_indices_raw = file_obj.read(struct.calcsize(REGISTER_ARRAY_PACK)) bit_indices = list(struct.unpack(REGISTER_ARRAY_PACK, bit_indices_raw)) if data.type.decode("utf8") == "q": @@ -148,7 +148,7 @@ def _read_registers(file_obj, num_registers): ) ) name = file_obj.read(data.name_size).decode("utf8") - REGISTER_ARRAY_PACK = "!%sI" % data.size + REGISTER_ARRAY_PACK = f"!{data.size}I" bit_indices_raw = file_obj.read(struct.calcsize(REGISTER_ARRAY_PACK)) bit_indices = list(struct.unpack(REGISTER_ARRAY_PACK, bit_indices_raw)) if data.type.decode("utf8") == "q": @@ -352,7 +352,7 @@ def _read_instruction( elif gate_name == "Clifford": gate_class = Clifford else: - raise AttributeError("Invalid instruction type: %s" % gate_name) + raise AttributeError(f"Invalid instruction type: {gate_name}") if instruction.label_size <= 0: label = None @@ -507,7 +507,7 @@ def _parse_custom_operation( if type_key == type_keys.CircuitInstruction.PAULI_EVOL_GATE: return definition - raise ValueError("Invalid custom instruction type '%s'" % type_str) + raise ValueError(f"Invalid custom instruction type '{type_str}'") def _read_pauli_evolution_gate(file_obj, version, vectors): @@ -1031,7 +1031,7 @@ def _write_registers(file_obj, in_circ_regs, full_bits): ) ) file_obj.write(reg_name) - REGISTER_ARRAY_PACK = "!%sq" % reg.size + REGISTER_ARRAY_PACK = f"!{reg.size}q" bit_indices = [] for bit in reg: bit_indices.append(bitmap.get(bit, -1)) diff --git a/qiskit/qpy/binary_io/value.py b/qiskit/qpy/binary_io/value.py index c9f0f9af4798..105d4364c07e 100644 --- a/qiskit/qpy/binary_io/value.py +++ b/qiskit/qpy/binary_io/value.py @@ -277,7 +277,7 @@ def _read_parameter_expression(file_obj): elif elem_key == type_keys.Value.PARAMETER_EXPRESSION: value = common.data_from_binary(binary_data, _read_parameter_expression) else: - raise exceptions.QpyError("Invalid parameter expression map type: %s" % elem_key) + raise exceptions.QpyError(f"Invalid parameter expression map type: {elem_key}") symbol_map[symbol] = value return ParameterExpression(symbol_map, expr_) @@ -311,7 +311,7 @@ def _read_parameter_expression_v3(file_obj, vectors, use_symengine): elif symbol_key == type_keys.Value.PARAMETER_VECTOR: symbol = _read_parameter_vec(file_obj, vectors) else: - raise exceptions.QpyError("Invalid parameter expression map type: %s" % symbol_key) + raise exceptions.QpyError(f"Invalid parameter expression map type: {symbol_key}") elem_key = type_keys.Value(elem_data.type) binary_data = file_obj.read(elem_data.size) @@ -331,7 +331,7 @@ def _read_parameter_expression_v3(file_obj, vectors, use_symengine): use_symengine=use_symengine, ) else: - raise exceptions.QpyError("Invalid parameter expression map type: %s" % elem_key) + raise exceptions.QpyError(f"Invalid parameter expression map type: {elem_key}") symbol_map[symbol] = value return ParameterExpression(symbol_map, expr_) diff --git a/qiskit/qpy/interface.py b/qiskit/qpy/interface.py index 34503dbab13b..d89117bc6a1c 100644 --- a/qiskit/qpy/interface.py +++ b/qiskit/qpy/interface.py @@ -304,10 +304,11 @@ def load( ): warnings.warn( "The qiskit version used to generate the provided QPY " - "file, %s, is newer than the current qiskit version %s. " + f"file, {'.'.join([str(x) for x in qiskit_version])}, " + f"is newer than the current qiskit version {__version__}. " "This may result in an error if the QPY file uses " "instructions not present in this current qiskit " - "version" % (".".join([str(x) for x in qiskit_version]), __version__) + "version" ) if data.qpy_version < 5: diff --git a/qiskit/quantum_info/operators/channel/quantum_channel.py b/qiskit/quantum_info/operators/channel/quantum_channel.py index 16df920e2e00..ff20feb5bf4f 100644 --- a/qiskit/quantum_info/operators/channel/quantum_channel.py +++ b/qiskit/quantum_info/operators/channel/quantum_channel.py @@ -66,12 +66,9 @@ def __init__( def __repr__(self): prefix = f"{self._channel_rep}(" pad = len(prefix) * " " - return "{}{},\n{}input_dims={}, output_dims={})".format( - prefix, - np.array2string(np.asarray(self.data), separator=", ", prefix=prefix), - pad, - self.input_dims(), - self.output_dims(), + return ( + f"{prefix}{np.array2string(np.asarray(self.data), separator=', ', prefix=prefix)}" + f",\n{pad}input_dims={self.input_dims()}, output_dims={self.output_dims()})" ) def __eq__(self, other: Self): diff --git a/qiskit/quantum_info/operators/channel/superop.py b/qiskit/quantum_info/operators/channel/superop.py index 19867696ec6a..f07652e22d79 100644 --- a/qiskit/quantum_info/operators/channel/superop.py +++ b/qiskit/quantum_info/operators/channel/superop.py @@ -355,8 +355,8 @@ def _append_instruction(self, obj, qargs=None): raise QiskitError(f"Cannot apply Instruction: {obj.name}") if not isinstance(obj.definition, QuantumCircuit): raise QiskitError( - "{} instruction definition is {}; " - "expected QuantumCircuit".format(obj.name, type(obj.definition)) + f"{obj.name} instruction definition is {type(obj.definition)}; " + "expected QuantumCircuit" ) qubit_indices = {bit: idx for idx, bit in enumerate(obj.definition.qubits)} for instruction in obj.definition.data: diff --git a/qiskit/quantum_info/operators/dihedral/dihedral_circuits.py b/qiskit/quantum_info/operators/dihedral/dihedral_circuits.py index 7104dced9df5..bfe76a2f3ca9 100644 --- a/qiskit/quantum_info/operators/dihedral/dihedral_circuits.py +++ b/qiskit/quantum_info/operators/dihedral/dihedral_circuits.py @@ -92,9 +92,7 @@ def _append_circuit(elem, circuit, qargs=None): raise QiskitError(f"Cannot apply Instruction: {gate.name}") if not isinstance(gate.definition, QuantumCircuit): raise QiskitError( - "{} instruction definition is {}; expected QuantumCircuit".format( - gate.name, type(gate.definition) - ) + f"{gate.name} instruction definition is {type(gate.definition)}; expected QuantumCircuit" ) flat_instr = gate.definition diff --git a/qiskit/quantum_info/operators/measures.py b/qiskit/quantum_info/operators/measures.py index 617e9f64b687..293c1236ed70 100644 --- a/qiskit/quantum_info/operators/measures.py +++ b/qiskit/quantum_info/operators/measures.py @@ -93,7 +93,7 @@ def process_fidelity( if channel.dim != target.dim: raise QiskitError( "Input quantum channel and target unitary must have the same " - "dimensions ({} != {}).".format(channel.dim, target.dim) + f"dimensions ({channel.dim} != {target.dim})." ) # Validate complete-positivity and trace-preserving diff --git a/qiskit/quantum_info/operators/op_shape.py b/qiskit/quantum_info/operators/op_shape.py index 4f95126ea148..42f05a8c53ab 100644 --- a/qiskit/quantum_info/operators/op_shape.py +++ b/qiskit/quantum_info/operators/op_shape.py @@ -193,7 +193,7 @@ def _validate(self, shape, raise_exception=False): if raise_exception: raise QiskitError( "Output dimensions do not match matrix shape " - "({} != {})".format(reduce(mul, self._dims_l), shape[0]) + f"({reduce(mul, self._dims_l)} != {shape[0]})" ) return False elif shape[0] != 2**self._num_qargs_l: @@ -207,7 +207,7 @@ def _validate(self, shape, raise_exception=False): if raise_exception: raise QiskitError( "Input dimensions do not match matrix shape " - "({} != {})".format(reduce(mul, self._dims_r), shape[1]) + f"({reduce(mul, self._dims_r)} != {shape[1]})" ) return False elif shape[1] != 2**self._num_qargs_r: @@ -430,7 +430,7 @@ def compose(self, other, qargs=None, front=False): if self._num_qargs_r != other._num_qargs_l or self._dims_r != other._dims_l: raise QiskitError( "Left and right compose dimensions don't match " - "({} != {})".format(self.dims_r(), other.dims_l()) + f"({self.dims_r()} != {other.dims_l()})" ) ret._dims_l = self._dims_l ret._dims_r = other._dims_r @@ -440,7 +440,7 @@ def compose(self, other, qargs=None, front=False): if self._num_qargs_l != other._num_qargs_r or self._dims_l != other._dims_r: raise QiskitError( "Left and right compose dimensions don't match " - "({} != {})".format(self.dims_l(), other.dims_r()) + f"({self.dims_l()} != {other.dims_r()})" ) ret._dims_l = other._dims_l ret._dims_r = self._dims_r @@ -453,15 +453,13 @@ def compose(self, other, qargs=None, front=False): ret._num_qargs_l = self._num_qargs_l if len(qargs) != other._num_qargs_l: raise QiskitError( - "Number of qargs does not match ({} != {})".format( - len(qargs), other._num_qargs_l - ) + f"Number of qargs does not match ({len(qargs)} != {other._num_qargs_l})" ) if self._dims_r or other._dims_r: if self.dims_r(qargs) != other.dims_l(): raise QiskitError( "Subsystem dimension do not match on specified qargs " - "{} != {}".format(self.dims_r(qargs), other.dims_l()) + f"{self.dims_r(qargs)} != {other.dims_l()}" ) dims_r = list(self.dims_r()) for i, dim in zip(qargs, other.dims_r()): @@ -475,15 +473,13 @@ def compose(self, other, qargs=None, front=False): ret._num_qargs_r = self._num_qargs_r if len(qargs) != other._num_qargs_r: raise QiskitError( - "Number of qargs does not match ({} != {})".format( - len(qargs), other._num_qargs_r - ) + f"Number of qargs does not match ({len(qargs)} != {other._num_qargs_r})" ) if self._dims_l or other._dims_l: if self.dims_l(qargs) != other.dims_r(): raise QiskitError( "Subsystem dimension do not match on specified qargs " - "{} != {}".format(self.dims_l(qargs), other.dims_r()) + f"{self.dims_l(qargs)} != {other.dims_r()}" ) dims_l = list(self.dims_l()) for i, dim in zip(qargs, other.dims_l()): @@ -508,26 +504,22 @@ def _validate_add(self, other, qargs=None): if self.dims_l(qargs) != other.dims_l(): raise QiskitError( "Cannot add shapes width different left " - "dimension on specified qargs {} != {}".format( - self.dims_l(qargs), other.dims_l() - ) + f"dimension on specified qargs {self.dims_l(qargs)} != {other.dims_l()}" ) if self.dims_r(qargs) != other.dims_r(): raise QiskitError( "Cannot add shapes width different total right " - "dimension on specified qargs{} != {}".format( - self.dims_r(qargs), other.dims_r() - ) + f"dimension on specified qargs{self.dims_r(qargs)} != {other.dims_r()}" ) elif self != other: if self._dim_l != other._dim_l: raise QiskitError( "Cannot add shapes width different total left " - "dimension {} != {}".format(self._dim_l, other._dim_l) + f"dimension {self._dim_l} != {other._dim_l}" ) if self._dim_r != other._dim_r: raise QiskitError( "Cannot add shapes width different total right " - "dimension {} != {}".format(self._dim_r, other._dim_r) + f"dimension {self._dim_r} != {other._dim_r}" ) return self diff --git a/qiskit/quantum_info/operators/operator.py b/qiskit/quantum_info/operators/operator.py index 016e337f082c..a4e93f364809 100644 --- a/qiskit/quantum_info/operators/operator.py +++ b/qiskit/quantum_info/operators/operator.py @@ -128,12 +128,9 @@ def __array__(self, dtype=None, copy=_numpy_compat.COPY_ONLY_IF_NEEDED): def __repr__(self): prefix = "Operator(" pad = len(prefix) * " " - return "{}{},\n{}input_dims={}, output_dims={})".format( - prefix, - np.array2string(self.data, separator=", ", prefix=prefix), - pad, - self.input_dims(), - self.output_dims(), + return ( + f"{prefix}{np.array2string(self.data, separator=', ', prefix=prefix)},\n" + f"{pad}input_dims={self.input_dims()}, output_dims={self.output_dims()})" ) def __eq__(self, other): @@ -763,10 +760,8 @@ def _append_instruction(self, obj, qargs=None): raise QiskitError(f"Cannot apply Operation: {obj.name}") if not isinstance(obj.definition, QuantumCircuit): raise QiskitError( - 'Operation "{}" ' - "definition is {} but expected QuantumCircuit.".format( - obj.name, type(obj.definition) - ) + f'Operation "{obj.name}" ' + f"definition is {type(obj.definition)} but expected QuantumCircuit." ) if obj.definition.global_phase: dimension = 2**obj.num_qubits diff --git a/qiskit/quantum_info/operators/predicates.py b/qiskit/quantum_info/operators/predicates.py index 57b7df64f268..f432195cd571 100644 --- a/qiskit/quantum_info/operators/predicates.py +++ b/qiskit/quantum_info/operators/predicates.py @@ -22,6 +22,7 @@ def matrix_equal(mat1, mat2, ignore_phase=False, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT, props=None): + # pylint: disable-next=consider-using-f-string """Test if two arrays are equal. The final comparison is implemented using Numpy.allclose. See its diff --git a/qiskit/quantum_info/operators/symplectic/base_pauli.py b/qiskit/quantum_info/operators/symplectic/base_pauli.py index e43eca4aff21..38e471f0b0a6 100644 --- a/qiskit/quantum_info/operators/symplectic/base_pauli.py +++ b/qiskit/quantum_info/operators/symplectic/base_pauli.py @@ -215,12 +215,12 @@ def commutes(self, other: BasePauli, qargs: list | None = None) -> np.ndarray: if qargs is not None and len(qargs) != other.num_qubits: raise QiskitError( "Number of qubits of other Pauli does not match number of " - "qargs ({} != {}).".format(other.num_qubits, len(qargs)) + f"qargs ({other.num_qubits} != {len(qargs)})." ) if qargs is None and self.num_qubits != other.num_qubits: raise QiskitError( "Number of qubits of other Pauli does not match the current " - "Pauli ({} != {}).".format(other.num_qubits, self.num_qubits) + f"Pauli ({other.num_qubits} != {self.num_qubits})." ) if qargs is not None: inds = list(qargs) @@ -262,15 +262,12 @@ def evolve( # Check dimension if qargs is not None and len(qargs) != other.num_qubits: raise QiskitError( - "Incorrect number of qubits for Clifford circuit ({} != {}).".format( - other.num_qubits, len(qargs) - ) + f"Incorrect number of qubits for Clifford circuit ({other.num_qubits} != {len(qargs)})." ) if qargs is None and self.num_qubits != other.num_qubits: raise QiskitError( - "Incorrect number of qubits for Clifford circuit ({} != {}).".format( - other.num_qubits, self.num_qubits - ) + f"Incorrect number of qubits for Clifford circuit " + f"({other.num_qubits} != {self.num_qubits})." ) # Evolve via Pauli @@ -571,9 +568,8 @@ def _append_circuit(self, circuit, qargs=None): raise QiskitError(f"Cannot apply Instruction: {gate.name}") if not isinstance(gate.definition, QuantumCircuit): raise QiskitError( - "{} instruction definition is {}; expected QuantumCircuit".format( - gate.name, type(gate.definition) - ) + f"{gate.name} instruction definition is {type(gate.definition)};" + f" expected QuantumCircuit" ) circuit = gate.definition diff --git a/qiskit/quantum_info/operators/symplectic/pauli.py b/qiskit/quantum_info/operators/symplectic/pauli.py index 8187c1ee41e6..867867eeb98a 100644 --- a/qiskit/quantum_info/operators/symplectic/pauli.py +++ b/qiskit/quantum_info/operators/symplectic/pauli.py @@ -344,7 +344,7 @@ def delete(self, qubits: int | list) -> Pauli: if max(qubits) > self.num_qubits - 1: raise QiskitError( "Qubit index is larger than the number of qubits " - "({}>{}).".format(max(qubits), self.num_qubits - 1) + f"({max(qubits)}>{self.num_qubits - 1})." ) if len(qubits) == self.num_qubits: raise QiskitError("Cannot delete all qubits of Pauli") @@ -379,12 +379,12 @@ def insert(self, qubits: int | list, value: Pauli) -> Pauli: if len(qubits) != value.num_qubits: raise QiskitError( "Number of indices does not match number of qubits for " - "the inserted Pauli ({}!={})".format(len(qubits), value.num_qubits) + f"the inserted Pauli ({len(qubits)}!={value.num_qubits})" ) if max(qubits) > ret.num_qubits - 1: raise QiskitError( "Index is too larger for combined Pauli number of qubits " - "({}>{}).".format(max(qubits), ret.num_qubits - 1) + f"({max(qubits)}>{ret.num_qubits - 1})." ) # Qubit positions for original op self_qubits = [i for i in range(ret.num_qubits) if i not in qubits] diff --git a/qiskit/quantum_info/operators/symplectic/pauli_list.py b/qiskit/quantum_info/operators/symplectic/pauli_list.py index 3d348d236387..f2e408dd9bd2 100644 --- a/qiskit/quantum_info/operators/symplectic/pauli_list.py +++ b/qiskit/quantum_info/operators/symplectic/pauli_list.py @@ -382,8 +382,8 @@ def delete(self, ind: int | list, qubit: bool = False) -> PauliList: if not qubit: if max(ind) >= len(self): raise QiskitError( - "Indices {} are not all less than the size" - " of the PauliList ({})".format(ind, len(self)) + f"Indices {ind} are not all less than the size" + f" of the PauliList ({len(self)})" ) z = np.delete(self._z, ind, axis=0) x = np.delete(self._x, ind, axis=0) @@ -394,8 +394,8 @@ def delete(self, ind: int | list, qubit: bool = False) -> PauliList: # Column (qubit) deletion if max(ind) >= self.num_qubits: raise QiskitError( - "Indices {} are not all less than the number of" - " qubits in the PauliList ({})".format(ind, self.num_qubits) + f"Indices {ind} are not all less than the number of" + f" qubits in the PauliList ({self.num_qubits})" ) z = np.delete(self._z, ind, axis=1) x = np.delete(self._x, ind, axis=1) @@ -432,8 +432,7 @@ def insert(self, ind: int, value: PauliList, qubit: bool = False) -> PauliList: if not qubit: if ind > size: raise QiskitError( - "Index {} is larger than the number of rows in the" - " PauliList ({}).".format(ind, size) + f"Index {ind} is larger than the number of rows in the" f" PauliList ({size})." ) base_z = np.insert(self._z, ind, value._z, axis=0) base_x = np.insert(self._x, ind, value._x, axis=0) @@ -443,8 +442,8 @@ def insert(self, ind: int, value: PauliList, qubit: bool = False) -> PauliList: # Column insertion if ind > self.num_qubits: raise QiskitError( - "Index {} is greater than number of qubits" - " in the PauliList ({})".format(ind, self.num_qubits) + f"Index {ind} is greater than number of qubits" + f" in the PauliList ({self.num_qubits})" ) if len(value) == 1: # Pad blocks to correct size @@ -461,7 +460,7 @@ def insert(self, ind: int, value: PauliList, qubit: bool = False) -> PauliList: raise QiskitError( "Input PauliList must have a single row, or" " the same number of rows as the Pauli Table" - " ({}).".format(size) + f" ({size})." ) # Build new array by blocks z = np.hstack([self.z[:, :ind], value_z, self.z[:, ind:]]) diff --git a/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py b/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py index 6204189be443..91d8d82decae 100644 --- a/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py +++ b/qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py @@ -172,7 +172,7 @@ def __init__( if self._coeffs.shape != (self._pauli_list.size,): raise QiskitError( "coeff vector is incorrect shape for number" - " of Paulis {} != {}".format(self._coeffs.shape, self._pauli_list.size) + f" of Paulis {self._coeffs.shape} != {self._pauli_list.size}" ) # Initialize LinearOp super().__init__(num_qubits=self._pauli_list.num_qubits) @@ -186,11 +186,9 @@ def __array__(self, dtype=None, copy=None): def __repr__(self): prefix = "SparsePauliOp(" pad = len(prefix) * " " - return "{}{},\n{}coeffs={})".format( - prefix, - self.paulis.to_labels(), - pad, - np.array2string(self.coeffs, separator=", "), + return ( + f"{prefix}{self.paulis.to_labels()},\n{pad}" + f"coeffs={np.array2string(self.coeffs, separator=', ')})" ) def __eq__(self, other): diff --git a/qiskit/quantum_info/states/densitymatrix.py b/qiskit/quantum_info/states/densitymatrix.py index 1c66d8bcf5cf..7826e3f22fec 100644 --- a/qiskit/quantum_info/states/densitymatrix.py +++ b/qiskit/quantum_info/states/densitymatrix.py @@ -123,11 +123,9 @@ def __eq__(self, other): def __repr__(self): prefix = "DensityMatrix(" pad = len(prefix) * " " - return "{}{},\n{}dims={})".format( - prefix, - np.array2string(self._data, separator=", ", prefix=prefix), - pad, - self._op_shape.dims_l(), + return ( + f"{prefix}{np.array2string(self._data, separator=', ', prefix=prefix)},\n" + f"{pad}dims={self._op_shape.dims_l()})" ) @property @@ -771,9 +769,8 @@ def _append_instruction(self, other, qargs=None): raise QiskitError(f"Cannot apply Instruction: {other.name}") if not isinstance(other.definition, QuantumCircuit): raise QiskitError( - "{} instruction definition is {}; expected QuantumCircuit".format( - other.name, type(other.definition) - ) + f"{other.name} instruction definition is {type(other.definition)};" + f" expected QuantumCircuit" ) qubit_indices = {bit: idx for idx, bit in enumerate(other.definition.qubits)} for instruction in other.definition: diff --git a/qiskit/quantum_info/states/statevector.py b/qiskit/quantum_info/states/statevector.py index df39ba42f915..7fa14eaac9da 100644 --- a/qiskit/quantum_info/states/statevector.py +++ b/qiskit/quantum_info/states/statevector.py @@ -117,11 +117,9 @@ def __eq__(self, other): def __repr__(self): prefix = "Statevector(" pad = len(prefix) * " " - return "{}{},\n{}dims={})".format( - prefix, - np.array2string(self._data, separator=", ", prefix=prefix), - pad, - self._op_shape.dims_l(), + return ( + f"{prefix}{np.array2string(self._data, separator=', ', prefix=prefix)},\n{pad}" + f"dims={self._op_shape.dims_l()})" ) @property @@ -940,9 +938,7 @@ def _evolve_instruction(statevec, obj, qargs=None): raise QiskitError(f"Cannot apply Instruction: {obj.name}") if not isinstance(obj.definition, QuantumCircuit): raise QiskitError( - "{} instruction definition is {}; expected QuantumCircuit".format( - obj.name, type(obj.definition) - ) + f"{obj.name} instruction definition is {type(obj.definition)}; expected QuantumCircuit" ) if obj.definition.global_phase: diff --git a/qiskit/result/counts.py b/qiskit/result/counts.py index 8b90ff0f0428..8168a3d21900 100644 --- a/qiskit/result/counts.py +++ b/qiskit/result/counts.py @@ -130,7 +130,7 @@ def most_frequent(self): max_values_counts = [x[0] for x in self.items() if x[1] == max_value] if len(max_values_counts) != 1: raise exceptions.QiskitError( - "Multiple values have the same maximum counts: %s" % ",".join(max_values_counts) + f"Multiple values have the same maximum counts: {','.join(max_values_counts)}" ) return max_values_counts[0] diff --git a/qiskit/result/mitigation/correlated_readout_mitigator.py b/qiskit/result/mitigation/correlated_readout_mitigator.py index 06cc89b4c52b..99e6f9ae4145 100644 --- a/qiskit/result/mitigation/correlated_readout_mitigator.py +++ b/qiskit/result/mitigation/correlated_readout_mitigator.py @@ -54,8 +54,8 @@ def __init__(self, assignment_matrix: np.ndarray, qubits: Optional[Iterable[int] else: if len(qubits) != matrix_qubits_num: raise QiskitError( - "The number of given qubits ({}) is different than the number of " - "qubits inferred from the matrices ({})".format(len(qubits), matrix_qubits_num) + f"The number of given qubits ({len(qubits)}) is different than the number of " + f"qubits inferred from the matrices ({matrix_qubits_num})" ) self._qubits = qubits self._num_qubits = len(self._qubits) diff --git a/qiskit/result/mitigation/local_readout_mitigator.py b/qiskit/result/mitigation/local_readout_mitigator.py index ad71911c2d75..197c3f00d9be 100644 --- a/qiskit/result/mitigation/local_readout_mitigator.py +++ b/qiskit/result/mitigation/local_readout_mitigator.py @@ -68,8 +68,8 @@ def __init__( else: if len(qubits) != len(assignment_matrices): raise QiskitError( - "The number of given qubits ({}) is different than the number of qubits " - "inferred from the matrices ({})".format(len(qubits), len(assignment_matrices)) + f"The number of given qubits ({len(qubits)}) is different than the number of qubits " + f"inferred from the matrices ({len(assignment_matrices)})" ) self._qubits = qubits self._num_qubits = len(self._qubits) diff --git a/qiskit/result/mitigation/utils.py b/qiskit/result/mitigation/utils.py index 26b5ee373488..823e2b69a6ca 100644 --- a/qiskit/result/mitigation/utils.py +++ b/qiskit/result/mitigation/utils.py @@ -120,9 +120,7 @@ def marganalize_counts( clbits_len = len(clbits) if not clbits is None else 0 if clbits_len not in (0, qubits_len): raise QiskitError( - "Num qubits ({}) does not match number of clbits ({}).".format( - qubits_len, clbits_len - ) + f"Num qubits ({qubits_len}) does not match number of clbits ({clbits_len})." ) counts = marginal_counts(counts, clbits) if clbits is None and qubits is not None: diff --git a/qiskit/result/models.py b/qiskit/result/models.py index 992810196713..83d9e4e78d5f 100644 --- a/qiskit/result/models.py +++ b/qiskit/result/models.py @@ -66,8 +66,7 @@ def __repr__(self): string_list = [] for field in self._data_attributes: string_list.append(f"{field}={getattr(self, field)}") - out = "ExperimentResultData(%s)" % ", ".join(string_list) - return out + return f"ExperimentResultData({', '.join(string_list)})" def to_dict(self): """Return a dictionary format representation of the ExperimentResultData @@ -157,23 +156,21 @@ def __init__( self._metadata.update(kwargs) def __repr__(self): - out = "ExperimentResult(shots={}, success={}, meas_level={}, data={}".format( - self.shots, - self.success, - self.meas_level, - self.data, + out = ( + f"ExperimentResult(shots={self.shots}, success={self.success}," + f" meas_level={self.meas_level}, data={self.data}" ) if hasattr(self, "header"): - out += ", header=%s" % self.header + out += f", header={self.header}" if hasattr(self, "status"): - out += ", status=%s" % self.status + out += f", status={self.status}" if hasattr(self, "seed"): - out += ", seed=%s" % self.seed + out += f", seed={self.seed}" if hasattr(self, "meas_return"): - out += ", meas_return=%s" % self.meas_return + out += f", meas_return={self.meas_return}" for key, value in self._metadata.items(): if isinstance(value, str): - value_str = "'%s'" % value + value_str = f"'{value}'" else: value_str = repr(value) out += f", {key}={value_str}" diff --git a/qiskit/result/result.py b/qiskit/result/result.py index c1792de56ae0..7df365785166 100644 --- a/qiskit/result/result.py +++ b/qiskit/result/result.py @@ -69,21 +69,14 @@ def __init__( def __repr__(self): out = ( - "Result(backend_name='%s', backend_version='%s', qobj_id='%s', " - "job_id='%s', success=%s, results=%s" - % ( - self.backend_name, - self.backend_version, - self.qobj_id, - self.job_id, - self.success, - self.results, - ) + f"Result(backend_name='{self.backend_name}', backend_version='{self.backend_version}'," + f" qobj_id='{self.qobj_id}', job_id='{self.job_id}', success={self.success}," + f" results={self.results}" ) out += f", date={self.date}, status={self.status}, header={self.header}" for key, value in self._metadata.items(): if isinstance(value, str): - value_str = "'%s'" % value + value_str = f"'{value}'" else: value_str = repr(value) out += f", {key}={value_str}" @@ -236,10 +229,10 @@ def get_memory(self, experiment=None): except KeyError as ex: raise QiskitError( - 'No memory for experiment "{}". ' + f'No memory for experiment "{repr(experiment)}". ' "Please verify that you either ran a measurement level 2 job " 'with the memory flag set, eg., "memory=True", ' - "or a measurement level 0/1 job.".format(repr(experiment)) + "or a measurement level 0/1 job." ) from ex def get_counts(self, experiment=None): @@ -377,14 +370,14 @@ def _get_experiment(self, key=None): ] if len(exp) == 0: - raise QiskitError('Data for experiment "%s" could not be found.' % key) + raise QiskitError(f'Data for experiment "{key}" could not be found.') if len(exp) == 1: exp = exp[0] else: warnings.warn( - 'Result object contained multiple results matching name "%s", ' + f'Result object contained multiple results matching name "{key}", ' "only first match will be returned. Use an integer index to " - "retrieve results for all entries." % key + "retrieve results for all entries." ) exp = exp[0] diff --git a/qiskit/scheduler/lowering.py b/qiskit/scheduler/lowering.py index fa622b205d3b..f0fb33957d9e 100644 --- a/qiskit/scheduler/lowering.py +++ b/qiskit/scheduler/lowering.py @@ -145,9 +145,9 @@ def get_measure_schedule(qubit_mem_slots: Dict[int, int]) -> CircuitPulseDef: elif isinstance(instruction.operation, Measure): if len(inst_qubits) != 1 and len(instruction.clbits) != 1: raise QiskitError( - "Qubit '{}' or classical bit '{}' errored because the " + f"Qubit '{inst_qubits}' or classical bit '{instruction.clbits}' errored because the " "circuit Measure instruction only takes one of " - "each.".format(inst_qubits, instruction.clbits) + "each." ) qubit_mem_slots[inst_qubits[0]] = clbit_indices[instruction.clbits[0]] else: diff --git a/qiskit/synthesis/linear/cnot_synth.py b/qiskit/synthesis/linear/cnot_synth.py index 5063577ed653..699523a7e75d 100644 --- a/qiskit/synthesis/linear/cnot_synth.py +++ b/qiskit/synthesis/linear/cnot_synth.py @@ -53,8 +53,7 @@ def synth_cnot_count_full_pmh( """ if not isinstance(state, (list, np.ndarray)): raise QiskitError( - "state should be of type list or numpy.ndarray, " - "but was of the type {}".format(type(state)) + f"state should be of type list or numpy.ndarray, but was of the type {type(state)}" ) state = np.array(state) # Synthesize lower triangular part diff --git a/qiskit/synthesis/two_qubit/two_qubit_decompose.py b/qiskit/synthesis/two_qubit/two_qubit_decompose.py index 41ba75c6b237..26a5b52521b2 100644 --- a/qiskit/synthesis/two_qubit/two_qubit_decompose.py +++ b/qiskit/synthesis/two_qubit/two_qubit_decompose.py @@ -116,7 +116,7 @@ def decompose_two_qubit_product_gate(special_unitary_matrix: np.ndarray): if deviation > 1.0e-13: raise QiskitError( "decompose_two_qubit_product_gate: decomposition failed: " - "deviation too large: {}".format(deviation) + f"deviation too large: {deviation}" ) return L, R, phase diff --git a/qiskit/transpiler/coupling.py b/qiskit/transpiler/coupling.py index 614e166050e8..27f98da68e7c 100644 --- a/qiskit/transpiler/coupling.py +++ b/qiskit/transpiler/coupling.py @@ -101,7 +101,7 @@ def add_physical_qubit(self, physical_qubit): raise CouplingError("Physical qubits should be integers.") if physical_qubit in self.physical_qubits: raise CouplingError( - "The physical qubit %s is already in the coupling graph" % physical_qubit + f"The physical qubit {physical_qubit} is already in the coupling graph" ) self.graph.add_node(physical_qubit) self._dist_matrix = None # invalidate @@ -188,9 +188,9 @@ def distance(self, physical_qubit1, physical_qubit2): CouplingError: if the qubits do not exist in the CouplingMap """ if physical_qubit1 >= self.size(): - raise CouplingError("%s not in coupling graph" % physical_qubit1) + raise CouplingError(f"{physical_qubit1} not in coupling graph") if physical_qubit2 >= self.size(): - raise CouplingError("%s not in coupling graph" % physical_qubit2) + raise CouplingError(f"{physical_qubit2} not in coupling graph") self.compute_distance_matrix() res = self._dist_matrix[physical_qubit1, physical_qubit2] if res == math.inf: diff --git a/qiskit/transpiler/layout.py b/qiskit/transpiler/layout.py index 1bebc7b84dc8..4117e2987bb6 100644 --- a/qiskit/transpiler/layout.py +++ b/qiskit/transpiler/layout.py @@ -98,8 +98,8 @@ def order_based_on_type(value1, value2): virtual = value1 else: raise LayoutError( - "The map (%s -> %s) has to be a (Bit -> integer)" - " or the other way around." % (type(value1), type(value2)) + f"The map ({type(value1)} -> {type(value2)}) has to be a (Bit -> integer)" + " or the other way around." ) return virtual, physical @@ -137,7 +137,7 @@ def __delitem__(self, key): else: raise LayoutError( "The key to remove should be of the form" - " Qubit or integer) and %s was provided" % (type(key),) + f" Qubit or integer) and {type(key)} was provided" ) def __len__(self): diff --git a/qiskit/transpiler/passes/basis/basis_translator.py b/qiskit/transpiler/passes/basis/basis_translator.py index bcac1f5d4faf..936613744b84 100644 --- a/qiskit/transpiler/passes/basis/basis_translator.py +++ b/qiskit/transpiler/passes/basis/basis_translator.py @@ -302,9 +302,7 @@ def _replace_node(self, dag, node, instr_map): if len(node.op.params) != len(target_params): raise TranspilerError( "Translation num_params not equal to op num_params." - "Op: {} {} Translation: {}\n{}".format( - node.op.params, node.op.name, target_params, target_dag - ) + f"Op: {node.op.params} {node.op.name} Translation: {target_params}\n{target_dag}" ) if node.op.params: parameter_map = dict(zip(target_params, node.op.params)) diff --git a/qiskit/transpiler/passes/basis/unroll_3q_or_more.py b/qiskit/transpiler/passes/basis/unroll_3q_or_more.py index 701e87dd9cd5..73e1d4ac5484 100644 --- a/qiskit/transpiler/passes/basis/unroll_3q_or_more.py +++ b/qiskit/transpiler/passes/basis/unroll_3q_or_more.py @@ -78,7 +78,7 @@ def run(self, dag): continue raise QiskitError( "Cannot unroll all 3q or more gates. " - "No rule to expand instruction %s." % node.op.name + f"No rule to expand instruction {node.op.name}." ) decomposition = circuit_to_dag(node.op.definition, copy_operations=False) decomposition = self.run(decomposition) # recursively unroll diff --git a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py index a54e4bfcb001..99bf95147ae2 100644 --- a/qiskit/transpiler/passes/basis/unroll_custom_definitions.py +++ b/qiskit/transpiler/passes/basis/unroll_custom_definitions.py @@ -95,9 +95,9 @@ def run(self, dag): if unrolled is None: # opaque node raise QiskitError( - "Cannot unroll the circuit to the given basis, %s. " - "Instruction %s not found in equivalence library " - "and no rule found to expand." % (str(self._basis_gates), node.op.name) + f"Cannot unroll the circuit to the given basis, {str(self._basis_gates)}. " + f"Instruction {node.op.name} not found in equivalence library " + "and no rule found to expand." ) decomposition = circuit_to_dag(unrolled, copy_operations=False) diff --git a/qiskit/transpiler/passes/calibration/rzx_builder.py b/qiskit/transpiler/passes/calibration/rzx_builder.py index 4cb576a23bc9..c153c3eeef33 100644 --- a/qiskit/transpiler/passes/calibration/rzx_builder.py +++ b/qiskit/transpiler/passes/calibration/rzx_builder.py @@ -204,7 +204,7 @@ def get_calibration(self, node_op: CircuitInst, qubits: list) -> Schedule | Sche if cal_type in [CRCalType.ECR_CX_FORWARD, CRCalType.ECR_FORWARD]: xgate = self._inst_map.get("x", qubits[0]) with builder.build( - default_alignment="sequential", name="rzx(%.3f)" % theta + default_alignment="sequential", name=f"rzx({theta:.3f})" ) as rzx_theta_native: for cr_tone, comp_tone in zip(cr_tones, comp_tones): with builder.align_left(): @@ -230,7 +230,7 @@ def get_calibration(self, node_op: CircuitInst, qubits: list) -> Schedule | Sche builder.call(szt, name="szt") with builder.build( - default_alignment="sequential", name="rzx(%.3f)" % theta + default_alignment="sequential", name=f"rzx({theta:.3f})" ) as rzx_theta_flip: builder.call(hadamard, name="hadamard") for cr_tone, comp_tone in zip(cr_tones, comp_tones): @@ -297,7 +297,7 @@ def get_calibration(self, node_op: CircuitInst, qubits: list) -> Schedule | Sche # RZXCalibrationNoEcho only good for forward CR direction if cal_type in [CRCalType.ECR_CX_FORWARD, CRCalType.ECR_FORWARD]: - with builder.build(default_alignment="left", name="rzx(%.3f)" % theta) as rzx_theta: + with builder.build(default_alignment="left", name=f"rzx({theta:.3f})") as rzx_theta: stretched_dur = self.rescale_cr_inst(cr_tones[0], 2 * theta) self.rescale_cr_inst(comp_tones[0], 2 * theta) # Placeholder to make pulse gate work diff --git a/qiskit/transpiler/passes/optimization/inverse_cancellation.py b/qiskit/transpiler/passes/optimization/inverse_cancellation.py index 958f53ef057d..f5523432c26e 100644 --- a/qiskit/transpiler/passes/optimization/inverse_cancellation.py +++ b/qiskit/transpiler/passes/optimization/inverse_cancellation.py @@ -53,8 +53,8 @@ def __init__(self, gates_to_cancel: List[Union[Gate, Tuple[Gate, Gate]]]): ) else: raise TranspilerError( - "InverseCancellation pass does not take input type {}. Input must be" - " a Gate.".format(type(gates)) + f"InverseCancellation pass does not take input type {type(gates)}. Input must be" + " a Gate." ) self.self_inverse_gates = [] diff --git a/qiskit/transpiler/passes/optimization/optimize_1q_gates.py b/qiskit/transpiler/passes/optimization/optimize_1q_gates.py index 9370fe7409f0..f8302b9232c0 100644 --- a/qiskit/transpiler/passes/optimization/optimize_1q_gates.py +++ b/qiskit/transpiler/passes/optimization/optimize_1q_gates.py @@ -308,7 +308,7 @@ def run(self, dag): if "u3" in self.basis: new_op = U3Gate(*right_parameters) else: - raise TranspilerError("It was not possible to use the basis %s" % self.basis) + raise TranspilerError(f"It was not possible to use the basis {self.basis}") dag.global_phase += right_global_phase diff --git a/qiskit/transpiler/passes/routing/sabre_swap.py b/qiskit/transpiler/passes/routing/sabre_swap.py index 28ae67b321cb..acb23f39ab09 100644 --- a/qiskit/transpiler/passes/routing/sabre_swap.py +++ b/qiskit/transpiler/passes/routing/sabre_swap.py @@ -218,7 +218,7 @@ def run(self, dag): elif self.heuristic == "decay": heuristic = Heuristic.Decay else: - raise TranspilerError("Heuristic %s not recognized." % self.heuristic) + raise TranspilerError(f"Heuristic {self.heuristic} not recognized.") disjoint_utils.require_layout_isolated_to_component( dag, self.coupling_map if self.target is None else self.target ) diff --git a/qiskit/transpiler/passes/routing/stochastic_swap.py b/qiskit/transpiler/passes/routing/stochastic_swap.py index ec7ea8149137..3732802b770e 100644 --- a/qiskit/transpiler/passes/routing/stochastic_swap.py +++ b/qiskit/transpiler/passes/routing/stochastic_swap.py @@ -357,9 +357,7 @@ def _mapper(self, circuit_graph, coupling_graph, trials=20): # Give up if we fail again if not success_flag: - raise TranspilerError( - "swap mapper failed: " + "layer %d, sublayer %d" % (i, j) - ) + raise TranspilerError(f"swap mapper failed: layer {i}, sublayer {j}") # Update the record of qubit positions # for each inner iteration diff --git a/qiskit/transpiler/passes/synthesis/high_level_synthesis.py b/qiskit/transpiler/passes/synthesis/high_level_synthesis.py index 150874a84c7d..668d10f32bcc 100644 --- a/qiskit/transpiler/passes/synthesis/high_level_synthesis.py +++ b/qiskit/transpiler/passes/synthesis/high_level_synthesis.py @@ -540,8 +540,8 @@ def _synthesize_op_using_plugins( if isinstance(plugin_specifier, str): if plugin_specifier not in hls_plugin_manager.method_names(op.name): raise TranspilerError( - "Specified method: %s not found in available plugins for %s" - % (plugin_specifier, op.name) + f"Specified method: {plugin_specifier} not found in available " + f"plugins for {op.name}" ) plugin_method = hls_plugin_manager.method(op.name, plugin_specifier) else: diff --git a/qiskit/transpiler/passes/utils/check_map.py b/qiskit/transpiler/passes/utils/check_map.py index 61ddc71d131e..437718ec27b4 100644 --- a/qiskit/transpiler/passes/utils/check_map.py +++ b/qiskit/transpiler/passes/utils/check_map.py @@ -85,10 +85,8 @@ def _recurse(self, dag, wire_map) -> bool: and not dag.has_calibration_for(node) and (wire_map[node.qargs[0]], wire_map[node.qargs[1]]) not in self.qargs ): - self.property_set["check_map_msg"] = "{}({}, {}) failed".format( - node.name, - wire_map[node.qargs[0]], - wire_map[node.qargs[1]], + self.property_set["check_map_msg"] = ( + f"{node.name}({wire_map[node.qargs[0]]}, {wire_map[node.qargs[1]]}) failed" ) return False return True diff --git a/qiskit/transpiler/passes/utils/error.py b/qiskit/transpiler/passes/utils/error.py index f2659ec052ff..44420582c1a3 100644 --- a/qiskit/transpiler/passes/utils/error.py +++ b/qiskit/transpiler/passes/utils/error.py @@ -43,7 +43,7 @@ def __init__(self, msg=None, action="raise"): if action in ["raise", "warn", "log"]: self.action = action else: - raise TranspilerError("Unknown action: %s" % action) + raise TranspilerError(f"Unknown action: {action}") def run(self, _): """Run the Error pass on `dag`.""" @@ -66,4 +66,4 @@ def run(self, _): logger = logging.getLogger(__name__) logger.info(msg) else: - raise TranspilerError("Unknown action: %s" % self.action) + raise TranspilerError(f"Unknown action: {self.action}") diff --git a/qiskit/transpiler/passes/utils/fixed_point.py b/qiskit/transpiler/passes/utils/fixed_point.py index fbef9d0a85ef..a85a7a8e6e7d 100644 --- a/qiskit/transpiler/passes/utils/fixed_point.py +++ b/qiskit/transpiler/passes/utils/fixed_point.py @@ -37,12 +37,12 @@ def __init__(self, property_to_check): def run(self, dag): """Run the FixedPoint pass on `dag`.""" current_value = self.property_set[self._property] - fixed_point_previous_property = "_fixed_point_previous_%s" % self._property + fixed_point_previous_property = f"_fixed_point_previous_{self._property}" if self.property_set[fixed_point_previous_property] is None: - self.property_set["%s_fixed_point" % self._property] = False + self.property_set[f"{self._property}_fixed_point"] = False else: fixed_point_reached = self.property_set[fixed_point_previous_property] == current_value - self.property_set["%s_fixed_point" % self._property] = fixed_point_reached + self.property_set[f"{self._property}_fixed_point"] = fixed_point_reached self.property_set[fixed_point_previous_property] = deepcopy(current_value) diff --git a/qiskit/transpiler/preset_passmanagers/common.py b/qiskit/transpiler/preset_passmanagers/common.py index 1b77e7dbd269..ec479f9e006b 100644 --- a/qiskit/transpiler/preset_passmanagers/common.py +++ b/qiskit/transpiler/preset_passmanagers/common.py @@ -518,7 +518,7 @@ def generate_translation_passmanager( ), ] else: - raise TranspilerError("Invalid translation method %s." % method) + raise TranspilerError(f"Invalid translation method {method}.") return PassManager(unroll) @@ -557,7 +557,7 @@ def generate_scheduling( try: scheduling.append(scheduler[scheduling_method](instruction_durations, target=target)) except KeyError as ex: - raise TranspilerError("Invalid scheduling method %s." % scheduling_method) from ex + raise TranspilerError(f"Invalid scheduling method {scheduling_method}.") from ex elif instruction_durations: # No scheduling. But do unit conversion for delays. def _contains_delay(property_set): diff --git a/qiskit/transpiler/target.py b/qiskit/transpiler/target.py index 53daa4ccbe65..8805deece50e 100644 --- a/qiskit/transpiler/target.py +++ b/qiskit/transpiler/target.py @@ -411,7 +411,7 @@ def add_instruction(self, instruction, properties=None, name=None): if properties is None: properties = {None: None} if instruction_name in self._gate_map: - raise AttributeError("Instruction %s is already in the target" % instruction_name) + raise AttributeError(f"Instruction {instruction_name} is already in the target") self._gate_name_map[instruction_name] = instruction if is_class: qargs_val = {None: None} @@ -1062,7 +1062,7 @@ def build_coupling_map(self, two_q_gate=None, filter_idle_qubits=False): for qargs, properties in self._gate_map[two_q_gate].items(): if len(qargs) != 2: raise ValueError( - "Specified two_q_gate: %s is not a 2 qubit instruction" % two_q_gate + f"Specified two_q_gate: {two_q_gate} is not a 2 qubit instruction" ) coupling_graph.add_edge(*qargs, {two_q_gate: properties}) cmap = CouplingMap() diff --git a/qiskit/user_config.py b/qiskit/user_config.py index 73a68eb6bfd5..0ca52fc5c8c0 100644 --- a/qiskit/user_config.py +++ b/qiskit/user_config.py @@ -63,9 +63,9 @@ def read_config_file(self): if circuit_drawer: if circuit_drawer not in ["text", "mpl", "latex", "latex_source", "auto"]: raise exceptions.QiskitUserConfigError( - "%s is not a valid circuit drawer backend. Must be " + f"{circuit_drawer} is not a valid circuit drawer backend. Must be " "either 'text', 'mpl', 'latex', 'latex_source', or " - "'auto'." % circuit_drawer + "'auto'." ) self.settings["circuit_drawer"] = circuit_drawer @@ -96,8 +96,8 @@ def read_config_file(self): if circuit_mpl_style: if not isinstance(circuit_mpl_style, str): warn( - "%s is not a valid mpl circuit style. Must be " - "a text string. Will not load style." % circuit_mpl_style, + f"{circuit_mpl_style} is not a valid mpl circuit style. Must be " + "a text string. Will not load style.", UserWarning, 2, ) @@ -112,8 +112,8 @@ def read_config_file(self): for path in cpath_list: if not os.path.exists(os.path.expanduser(path)): warn( - "%s is not a valid circuit mpl style path." - " Correct the path in ~/.qiskit/settings.conf." % path, + f"{path} is not a valid circuit mpl style path." + " Correct the path in ~/.qiskit/settings.conf.", UserWarning, 2, ) diff --git a/qiskit/visualization/circuit/circuit_visualization.py b/qiskit/visualization/circuit/circuit_visualization.py index a1672dc1676c..146de9d32dee 100644 --- a/qiskit/visualization/circuit/circuit_visualization.py +++ b/qiskit/visualization/circuit/circuit_visualization.py @@ -345,8 +345,8 @@ def check_clbit_in_inst(circuit, cregbundle): ) else: raise VisualizationError( - "Invalid output type %s selected. The only valid choices " - "are text, latex, latex_source, and mpl" % output + f"Invalid output type {output} selected. The only valid choices " + "are text, latex, latex_source, and mpl" ) if image and interactive: image.show() diff --git a/qiskit/visualization/circuit/latex.py b/qiskit/visualization/circuit/latex.py index 9341126bcd1a..4cb233277c0d 100644 --- a/qiskit/visualization/circuit/latex.py +++ b/qiskit/visualization/circuit/latex.py @@ -415,7 +415,7 @@ def _build_latex_array(self): cwire_list = [] if len(wire_list) == 1 and not node.cargs: - self._latex[wire_list[0]][column] = "\\gate{%s}" % gate_text + self._latex[wire_list[0]][column] = f"\\gate{{{gate_text}}}" elif isinstance(op, ControlledGate): num_cols_op = self._build_ctrl_gate(op, gate_text, wire_list, column) @@ -443,20 +443,20 @@ def _build_multi_gate(self, op, gate_text, wire_list, cwire_list, col): self._latex[wire_min][col] = ( f"\\multigate{{{wire_max - wire_min}}}{{{gate_text}}}_" + "<" * (len(str(wire_ind)) + 2) - + "{%s}" % wire_ind + + f"{{{wire_ind}}}" ) for wire in range(wire_min + 1, wire_max + 1): if wire < cwire_start: - ghost_box = "\\ghost{%s}" % gate_text + ghost_box = f"\\ghost{{{gate_text}}}" if wire in wire_list: wire_ind = wire_list.index(wire) else: - ghost_box = "\\cghost{%s}" % gate_text + ghost_box = f"\\cghost{{{gate_text}}}" if wire in cwire_list: wire_ind = cwire_list.index(wire) if wire in wire_list + cwire_list: self._latex[wire][col] = ( - ghost_box + "_" + "<" * (len(str(wire_ind)) + 2) + "{%s}" % wire_ind + ghost_box + "_" + "<" * (len(str(wire_ind)) + 2) + f"{{{wire_ind}}}" ) else: self._latex[wire][col] = ghost_box @@ -484,7 +484,7 @@ def _build_ctrl_gate(self, op, gate_text, wire_list, col): elif isinstance(op.base_gate, (U1Gate, PhaseGate)): num_cols_op = self._build_symmetric_gate(op, gate_text, wire_list, col) else: - self._latex[wireqargs[0]][col] = "\\gate{%s}" % gate_text + self._latex[wireqargs[0]][col] = f"\\gate{{{gate_text}}}" else: # Treat special cases of swap and rzz gates if isinstance(op.base_gate, (SwapGate, RZZGate)): @@ -527,7 +527,7 @@ def _build_symmetric_gate(self, op, gate_text, wire_list, col): ) self._latex[wire_last][col] = "\\control \\qw" # Put side text to the right between bottom wire in wire_list and the one above it - self._latex[wire_max - 1][col + 1] = "\\dstick{\\hspace{2.0em}%s} \\qw" % gate_text + self._latex[wire_max - 1][col + 1] = f"\\dstick{{\\hspace{{2.0em}}{gate_text}}} \\qw" return 4 # num_cols for side text gates def _build_measure(self, node, col): @@ -544,11 +544,9 @@ def _build_measure(self, node, col): idx_str = str(self._circuit.find_bit(node.cargs[0]).registers[0][1]) else: wire2 = self._wire_map[node.cargs[0]] - - self._latex[wire2][col] = "\\dstick{_{_{\\hspace{%sem}%s}}} \\cw \\ar @{<=} [-%s,0]" % ( - cond_offset, - idx_str, - str(wire2 - wire1), + self._latex[wire2][col] = ( + f"\\dstick{{_{{_{{\\hspace{{{cond_offset}em}}{idx_str}}}}}}} " + f"\\cw \\ar @{{<=}} [-{str(wire2 - wire1)},0]" ) else: wire2 = self._wire_map[node.cargs[0]] @@ -573,7 +571,7 @@ def _build_barrier(self, node, col): if node.op.label is not None: pos = indexes[0] label = node.op.label.replace(" ", "\\,") - self._latex[pos][col] = "\\cds{0}{^{\\mathrm{%s}}}" % label + self._latex[pos][col] = f"\\cds{{0}}{{^{{\\mathrm{{{label}}}}}}}" def _add_controls(self, wire_list, ctrlqargs, ctrl_state, col): """Add one or more controls to a gate""" @@ -615,11 +613,10 @@ def _add_condition(self, op, wire_list, col): ) gap = cwire - max(wire_list) control = "\\control" if op.condition[1] else "\\controlo" - self._latex[cwire][col] = f"{control}" + " \\cw^(%s){^{\\mathtt{%s}}} \\cwx[-%s]" % ( - meas_offset, - label, - str(gap), - ) + self._latex[cwire][ + col + ] = f"{control} \\cw^({meas_offset}){{^{{\\mathtt{{{label}}}}}}} \\cwx[-{str(gap)}]" + # If condition is a register and cregbundle is false else: # First sort the val_bits in the order of the register bits in the circuit diff --git a/qiskit/visualization/circuit/matplotlib.py b/qiskit/visualization/circuit/matplotlib.py index 0076073fb8e4..9c4fa25309fc 100644 --- a/qiskit/visualization/circuit/matplotlib.py +++ b/qiskit/visualization/circuit/matplotlib.py @@ -371,7 +371,7 @@ def draw(self, filename=None, verbose=False): # Once the scaling factor has been determined, the global phase, register names # and numbers, wires, and gates are drawn if self._global_phase: - plt_mod.text(xl, yt, "Global Phase: %s" % pi_check(self._global_phase, output="mpl")) + plt_mod.text(xl, yt, f"Global Phase: {pi_check(self._global_phase, output='mpl')}") self._draw_regs_wires(num_folds, xmax, max_x_index, qubits_dict, clbits_dict, glob_data) self._draw_ops( self._nodes, diff --git a/qiskit/visualization/circuit/text.py b/qiskit/visualization/circuit/text.py index bec1ccf4a3ee..e9b7aa819e9b 100644 --- a/qiskit/visualization/circuit/text.py +++ b/qiskit/visualization/circuit/text.py @@ -759,7 +759,7 @@ def _repr_html_(self): "background: #fff0;" "line-height: 1.1;" 'font-family: "Courier New",Courier,monospace">' - "%s" % self.single_string() + f"{self.single_string()}" ) def __repr__(self): @@ -780,8 +780,9 @@ def single_string(self): ) except (UnicodeEncodeError, UnicodeDecodeError): warn( - "The encoding %s has a limited charset. Consider a different encoding in your " - "environment. UTF-8 is being used instead" % self.encoding, + f"The encoding {self.encoding} has a limited charset." + " Consider a different encoding in your " + "environment. UTF-8 is being used instead", RuntimeWarning, ) self.encoding = "utf-8" @@ -861,7 +862,7 @@ def lines(self, line_length=None): lines = [] if self.global_phase: - lines.append("global phase: %s" % pi_check(self.global_phase, ndigits=5)) + lines.append(f"global phase: {pi_check(self.global_phase, ndigits=5)}") for layer_group in layer_groups: wires = list(zip(*layer_group)) @@ -1168,7 +1169,7 @@ def add_connected_gate(node, gates, layer, current_cons, gate_wire_map): elif isinstance(op, RZZGate): # rzz - connection_label = "ZZ%s" % params + connection_label = f"ZZ{params}" gates = [Bullet(conditional=conditional), Bullet(conditional=conditional)] add_connected_gate(node, gates, layer, current_cons, gate_wire_map) @@ -1211,7 +1212,7 @@ def add_connected_gate(node, gates, layer, current_cons, gate_wire_map): add_connected_gate(node, gates, layer, current_cons, gate_wire_map) elif base_gate.name == "rzz": # crzz - connection_label = "ZZ%s" % params + connection_label = f"ZZ{params}" gates += [Bullet(conditional=conditional), Bullet(conditional=conditional)] elif len(rest) > 1: top_connect = "┴" if controlled_top else None diff --git a/qiskit/visualization/dag_visualization.py b/qiskit/visualization/dag_visualization.py index 73b9c30f6dc8..ad2fca6e9bcf 100644 --- a/qiskit/visualization/dag_visualization.py +++ b/qiskit/visualization/dag_visualization.py @@ -152,7 +152,7 @@ def node_attr_func(node): n["fillcolor"] = "lightblue" return n else: - raise VisualizationError("Unrecognized style %s for the dag_drawer." % style) + raise VisualizationError(f"Unrecognized style {style} for the dag_drawer.") edge_attr_func = None @@ -197,7 +197,7 @@ def node_attr_func(node): n["fillcolor"] = "red" return n else: - raise VisualizationError("Invalid style %s" % style) + raise VisualizationError(f"Invalid style {style}") def edge_attr_func(edge): e = {} diff --git a/qiskit/visualization/pulse_v2/core.py b/qiskit/visualization/pulse_v2/core.py index d60f2db030d0..20686f6fb4f6 100644 --- a/qiskit/visualization/pulse_v2/core.py +++ b/qiskit/visualization/pulse_v2/core.py @@ -220,7 +220,7 @@ def load_program( elif isinstance(program, (pulse.Waveform, pulse.SymbolicPulse)): self._waveform_loader(program) else: - raise VisualizationError("Data type %s is not supported." % type(program)) + raise VisualizationError(f"Data type {type(program)} is not supported.") # update time range self.set_time_range(0, program.duration, seconds=False) diff --git a/qiskit/visualization/pulse_v2/generators/frame.py b/qiskit/visualization/pulse_v2/generators/frame.py index 394f4b4aaf84..8b71b8596bb4 100644 --- a/qiskit/visualization/pulse_v2/generators/frame.py +++ b/qiskit/visualization/pulse_v2/generators/frame.py @@ -264,10 +264,9 @@ def gen_raw_operand_values_compact( freq_sci_notation = "0.0" else: abs_freq = np.abs(data.frame.freq) - freq_sci_notation = "{base:.1f}e{exp:d}".format( - base=data.frame.freq / (10 ** int(np.floor(np.log10(abs_freq)))), - exp=int(np.floor(np.log10(abs_freq))), - ) + base = data.frame.freq / (10 ** int(np.floor(np.log10(abs_freq)))) + exponent = int(np.floor(np.log10(abs_freq))) + freq_sci_notation = f"{base:.1f}e{exponent:d}" frame_info = f"{data.frame.phase:.2f}\n{freq_sci_notation}" text = drawings.TextData( diff --git a/qiskit/visualization/pulse_v2/generators/waveform.py b/qiskit/visualization/pulse_v2/generators/waveform.py index b0d90b895c7a..e770f271c454 100644 --- a/qiskit/visualization/pulse_v2/generators/waveform.py +++ b/qiskit/visualization/pulse_v2/generators/waveform.py @@ -203,11 +203,10 @@ def gen_ibmq_latex_waveform_name( if frac.numerator == 1: angle = rf"\pi/{frac.denominator:d}" else: - angle = r"{num:d}/{denom:d} \pi".format( - num=frac.numerator, denom=frac.denominator - ) + angle = rf"{frac.numerator:d}/{frac.denominator:d} \pi" else: # single qubit pulse + # pylint: disable-next=consider-using-f-string op_name = r"{{\rm {}}}".format(match_dict["op"]) angle_val = match_dict["angle"] if angle_val is None: @@ -217,9 +216,7 @@ def gen_ibmq_latex_waveform_name( if frac.numerator == 1: angle = rf"\pi/{frac.denominator:d}" else: - angle = r"{num:d}/{denom:d} \pi".format( - num=frac.numerator, denom=frac.denominator - ) + angle = rf"{frac.numerator:d}/{frac.denominator:d} \pi" latex_name = rf"{op_name}({sign}{angle})" else: latex_name = None @@ -490,7 +487,7 @@ def _draw_opaque_waveform( fill_objs.append(box_obj) # parameter name - func_repr = "{func}({params})".format(func=pulse_shape, params=", ".join(pnames)) + func_repr = f"{pulse_shape}({', '.join(pnames)})" text_style = { "zorder": formatter["layer.annotate"], @@ -630,8 +627,7 @@ def _parse_waveform( meta.update(acq_data) else: raise VisualizationError( - "Unsupported instruction {inst} by " - "filled envelope.".format(inst=inst.__class__.__name__) + f"Unsupported instruction {inst.__class__.__name__} by " "filled envelope." ) meta.update( diff --git a/qiskit/visualization/pulse_v2/layouts.py b/qiskit/visualization/pulse_v2/layouts.py index 6b39dceaf567..13b42e394e94 100644 --- a/qiskit/visualization/pulse_v2/layouts.py +++ b/qiskit/visualization/pulse_v2/layouts.py @@ -373,11 +373,7 @@ def detail_title(program: Union[pulse.Waveform, pulse.Schedule], device: DrawerB # add program duration dt = device.dt * 1e9 if device.dt else 1.0 - title_str.append( - "Duration: {dur:.1f} {unit}".format( - dur=program.duration * dt, unit="ns" if device.dt else "dt" - ) - ) + title_str.append(f"Duration: {program.duration * dt:.1f} {'ns' if device.dt else 'dt'}") # add device name if device.backend_name != "no-backend": diff --git a/qiskit/visualization/pulse_v2/plotters/matplotlib.py b/qiskit/visualization/pulse_v2/plotters/matplotlib.py index e92a34189994..1788a1254894 100644 --- a/qiskit/visualization/pulse_v2/plotters/matplotlib.py +++ b/qiskit/visualization/pulse_v2/plotters/matplotlib.py @@ -119,8 +119,7 @@ def draw(self): self.ax.add_patch(box) else: raise VisualizationError( - "Data {name} is not supported " - "by {plotter}".format(name=data, plotter=self.__class__.__name__) + f"Data {data} is not supported " f"by {self.__class__.__name__}" ) # axis break for pos in axis_config.axis_break_pos: diff --git a/qiskit/visualization/state_visualization.py b/qiskit/visualization/state_visualization.py index e862b0208e28..0e47a5fe6d72 100644 --- a/qiskit/visualization/state_visualization.py +++ b/qiskit/visualization/state_visualization.py @@ -971,10 +971,10 @@ def plot_state_qsphere( if show_state_phases: element_angle = (np.angle(state[i]) + (np.pi * 4)) % (np.pi * 2) if use_degrees: - element_text += "\n$%.1f^\\circ$" % (element_angle * 180 / np.pi) + element_text += f"\n${element_angle * 180 / np.pi:.1f}^\\circ$" else: element_angle = pi_check(element_angle, ndigits=3).replace("pi", "\\pi") - element_text += "\n$%s$" % (element_angle) + element_text += f"\n${element_angle}$" ax.text( xvalue_text, yvalue_text, @@ -1463,11 +1463,10 @@ def state_drawer(state, output=None, **drawer_args): return draw_func(state, **drawer_args) except KeyError as err: raise ValueError( - """'{}' is not a valid option for drawing {} objects. Please choose from: + f"""'{output}' is not a valid option for drawing {type(state).__name__} + objects. Please choose from: 'text', 'latex', 'latex_source', 'qsphere', 'hinton', - 'bloch', 'city' or 'paulivec'.""".format( - output, type(state).__name__ - ) + 'bloch', 'city' or 'paulivec'.""" ) from err diff --git a/qiskit/visualization/timeline/plotters/matplotlib.py b/qiskit/visualization/timeline/plotters/matplotlib.py index 126d0981feda..daae6fe2558f 100644 --- a/qiskit/visualization/timeline/plotters/matplotlib.py +++ b/qiskit/visualization/timeline/plotters/matplotlib.py @@ -132,8 +132,7 @@ def draw(self): else: raise VisualizationError( - "Data {name} is not supported by {plotter}" - "".format(name=data, plotter=self.__class__.__name__) + f"Data {data} is not supported by {self.__class__.__name__}" ) def _time_bucket_outline( diff --git a/test/benchmarks/circuit_construction.py b/test/benchmarks/circuit_construction.py index 71c079476cd8..6c6c8733d25f 100644 --- a/test/benchmarks/circuit_construction.py +++ b/test/benchmarks/circuit_construction.py @@ -52,7 +52,7 @@ def time_circuit_copy(self, _, __): def build_parameterized_circuit(width, gates, param_count): - params = [Parameter("param-%s" % x) for x in range(param_count)] + params = [Parameter(f"param-{x}") for x in range(param_count)] param_iter = itertools.cycle(params) qr = QuantumRegister(width) diff --git a/test/python/circuit/test_circuit_qasm.py b/test/python/circuit/test_circuit_qasm.py index 121ad7222f4e..c1ece0230d39 100644 --- a/test/python/circuit/test_circuit_qasm.py +++ b/test/python/circuit/test_circuit_qasm.py @@ -167,7 +167,7 @@ def test_circuit_qasm_with_multiple_composite_circuits_with_same_name(self): my_gate_inst2_id = id(circuit.data[-1].operation) circuit.append(my_gate_inst3, [qr[0]]) my_gate_inst3_id = id(circuit.data[-1].operation) - + # pylint: disable-next=consider-using-f-string expected_qasm = """OPENQASM 2.0; include "qelib1.inc"; gate my_gate q0 {{ h q0; }} diff --git a/test/python/circuit/test_circuit_registers.py b/test/python/circuit/test_circuit_registers.py index 3de2a451877b..7ef8751da0eb 100644 --- a/test/python/circuit/test_circuit_registers.py +++ b/test/python/circuit/test_circuit_registers.py @@ -97,7 +97,7 @@ def test_numpy_array_of_registers(self): """Test numpy array of Registers . See https://github.com/Qiskit/qiskit-terra/issues/1898 """ - qrs = [QuantumRegister(2, name="q%s" % i) for i in range(5)] + qrs = [QuantumRegister(2, name=f"q{i}") for i in range(5)] qreg_array = np.array([], dtype=object, ndmin=1) qreg_array = np.append(qreg_array, qrs) diff --git a/test/python/circuit/test_instructions.py b/test/python/circuit/test_instructions.py index 4ac69278fd44..dbda9262f15b 100644 --- a/test/python/circuit/test_instructions.py +++ b/test/python/circuit/test_instructions.py @@ -423,17 +423,15 @@ def test_repr_of_instructions(self): ins1 = Instruction("test_instruction", 3, 5, [0, 1, 2, 3]) self.assertEqual( repr(ins1), - "Instruction(name='{}', num_qubits={}, num_clbits={}, params={})".format( - ins1.name, ins1.num_qubits, ins1.num_clbits, ins1.params - ), + f"Instruction(name='{ins1.name}', num_qubits={ins1.num_qubits}, " + f"num_clbits={ins1.num_clbits}, params={ins1.params})", ) ins2 = random_circuit(num_qubits=4, depth=4, measure=True).to_instruction() self.assertEqual( repr(ins2), - "Instruction(name='{}', num_qubits={}, num_clbits={}, params={})".format( - ins2.name, ins2.num_qubits, ins2.num_clbits, ins2.params - ), + f"Instruction(name='{ins2.name}', num_qubits={ins2.num_qubits}, " + f"num_clbits={ins2.num_clbits}, params={ins2.params})", ) def test_instruction_condition_bits(self): diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index fd63057cff8d..feab3002f582 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -58,8 +58,8 @@ def raise_if_parameter_table_invalid(circuit): if circuit_parameters != table_parameters: raise CircuitError( "Circuit/ParameterTable Parameter mismatch. " - "Circuit parameters: {}. " - "Table parameters: {}.".format(circuit_parameters, table_parameters) + f"Circuit parameters: {circuit_parameters}. " + f"Table parameters: {table_parameters}." ) # Assert parameter locations in table are present in circuit. @@ -75,16 +75,15 @@ def raise_if_parameter_table_invalid(circuit): if not isinstance(instr.params[param_index], ParameterExpression): raise CircuitError( "ParameterTable instruction does not have a " - "ParameterExpression at param_index {}: {}." - "".format(param_index, instr) + f"ParameterExpression at param_index {param_index}: {instr}." ) if parameter not in instr.params[param_index].parameters: raise CircuitError( "ParameterTable instruction parameters does " "not match ParameterTable key. Instruction " - "parameters: {} ParameterTable key: {}." - "".format(instr.params[param_index].parameters, parameter) + f"parameters: {instr.params[param_index].parameters}" + f" ParameterTable key: {parameter}." ) # Assert circuit has no other parameter locations other than those in table. @@ -99,8 +98,8 @@ def raise_if_parameter_table_invalid(circuit): ): raise CircuitError( "Found parameterized instruction not " - "present in table. Instruction: {} " - "param_index: {}".format(instruction.operation, param_index) + f"present in table. Instruction: {instruction.operation} " + f"param_index: {param_index}" ) diff --git a/test/python/dagcircuit/test_dagcircuit.py b/test/python/dagcircuit/test_dagcircuit.py index 14033e522c62..0fcff29e5b40 100644 --- a/test/python/dagcircuit/test_dagcircuit.py +++ b/test/python/dagcircuit/test_dagcircuit.py @@ -83,8 +83,8 @@ def raise_if_dagcircuit_invalid(dag): ] if edges_outside_wires: raise DAGCircuitError( - "multi_graph contains one or more edges ({}) " - "not found in DAGCircuit.wires ({}).".format(edges_outside_wires, dag.wires) + f"multi_graph contains one or more edges ({edges_outside_wires}) " + f"not found in DAGCircuit.wires ({dag.wires})." ) # Every wire should have exactly one input node and one output node. @@ -134,9 +134,7 @@ def raise_if_dagcircuit_invalid(dag): all_bits = node_qubits | node_clbits | node_cond_bits assert in_wires == all_bits, f"In-edge wires {in_wires} != node bits {all_bits}" - assert out_wires == all_bits, "Out-edge wires {} != node bits {}".format( - out_wires, all_bits - ) + assert out_wires == all_bits, f"Out-edge wires {out_wires} != node bits {all_bits}" class TestDagRegisters(QiskitTestCase): diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index 101e35acc8e1..d5c5507b3b8e 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -105,7 +105,7 @@ def setUpClass(cls): ) def test_circuit_on_fake_backend_v2(self, backend, optimization_level): if not optionals.HAS_AER and backend.num_qubits > 20: - self.skipTest("Unable to run fake_backend %s without qiskit-aer" % backend.name) + self.skipTest(f"Unable to run fake_backend {backend.name} without qiskit-aer") job = backend.run( transpile( self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level @@ -126,8 +126,7 @@ def test_circuit_on_fake_backend_v2(self, backend, optimization_level): def test_circuit_on_fake_backend(self, backend, optimization_level): if not optionals.HAS_AER and backend.configuration().num_qubits > 20: self.skipTest( - "Unable to run fake_backend %s without qiskit-aer" - % backend.configuration().backend_name + f"Unable to run fake_backend {backend.configuration().backend_name} without qiskit-aer" ) job = backend.run( transpile( @@ -202,7 +201,7 @@ def test_defaults_to_dict(self, backend): self.assertGreater(i, 1e6) self.assertGreater(i, 1e6) else: - self.skipTest("Backend %s does not have defaults" % backend) + self.skipTest(f"Backend {backend} does not have defaults") def test_delay_circuit(self): backend = Fake27QPulseV1() diff --git a/test/python/quantum_info/operators/symplectic/test_clifford.py b/test/python/quantum_info/operators/symplectic/test_clifford.py index 3585efb9f646..043a9eca78b6 100644 --- a/test/python/quantum_info/operators/symplectic/test_clifford.py +++ b/test/python/quantum_info/operators/symplectic/test_clifford.py @@ -150,7 +150,7 @@ def test_append_1_qubit_gate(self): "sx", "sxdg", ): - with self.subTest(msg="append gate %s" % gate_name): + with self.subTest(msg=f"append gate {gate_name}"): cliff = Clifford([[1, 0], [0, 1]]) cliff = _append_operation(cliff, gate_name, [0]) value_table = cliff.tableau[:, :-1] @@ -170,7 +170,7 @@ def test_1_qubit_identity_relations(self): """Tests identity relations for 1-qubit gates""" for gate_name in ("x", "y", "z", "h"): - with self.subTest(msg="identity for gate %s" % gate_name): + with self.subTest(msg=f"identity for gate {gate_name}"): cliff = Clifford([[1, 0], [0, 1]]) cliff1 = cliff.copy() cliff = _append_operation(cliff, gate_name, [0]) @@ -181,7 +181,7 @@ def test_1_qubit_identity_relations(self): inv_gates = ["sdg", "sinv", "w"] for gate_name, inv_gate in zip(gates, inv_gates): - with self.subTest(msg="identity for gate %s" % gate_name): + with self.subTest(msg=f"identity for gate {gate_name}"): cliff = Clifford([[1, 0], [0, 1]]) cliff1 = cliff.copy() cliff = _append_operation(cliff, gate_name, [0]) @@ -203,7 +203,7 @@ def test_1_qubit_mult_relations(self): ] for rel in rels: - with self.subTest(msg="relation %s" % rel): + with self.subTest(msg=f"relation {rel}"): split_rel = rel.split() cliff = Clifford([[1, 0], [0, 1]]) cliff1 = cliff.copy() @@ -227,7 +227,7 @@ def test_1_qubit_conj_relations(self): ] for rel in rels: - with self.subTest(msg="relation %s" % rel): + with self.subTest(msg=f"relation {rel}"): split_rel = rel.split() cliff = Clifford([[1, 0], [0, 1]]) cliff1 = cliff.copy() diff --git a/test/python/quantum_info/states/test_densitymatrix.py b/test/python/quantum_info/states/test_densitymatrix.py index 4f5c728604b5..cf6ad3c35090 100644 --- a/test/python/quantum_info/states/test_densitymatrix.py +++ b/test/python/quantum_info/states/test_densitymatrix.py @@ -398,7 +398,7 @@ def test_to_dict(self): target = {} for i in range(2): for j in range(3): - key = "{1}{0}|{1}{0}".format(i, j) + key = f"{j}{i}|{j}{i}" target[key] = 2 * j + i + 1 self.assertDictAlmostEqual(target, rho.to_dict()) @@ -407,7 +407,7 @@ def test_to_dict(self): target = {} for i in range(2): for j in range(11): - key = "{1},{0}|{1},{0}".format(i, j) + key = f"{j},{i}|{j},{i}" target[key] = 2 * j + i + 1 self.assertDictAlmostEqual(target, vec.to_dict()) diff --git a/test/python/result/test_mitigators.py b/test/python/result/test_mitigators.py index d290fc8ed486..66662bb587e1 100644 --- a/test/python/result/test_mitigators.py +++ b/test/python/result/test_mitigators.py @@ -140,22 +140,16 @@ def test_mitigation_improvement(self): self.assertLess( mitigated_error, unmitigated_error * 0.8, - "Mitigator {} did not improve circuit {} measurements".format( - mitigator, circuit_name - ), + f"Mitigator {mitigator} did not improve circuit {circuit_name} measurements", ) mitigated_stddev_upper_bound = mitigated_quasi_probs._stddev_upper_bound max_unmitigated_stddev = max(unmitigated_stddev.values()) self.assertGreaterEqual( mitigated_stddev_upper_bound, max_unmitigated_stddev, - "Mitigator {} on circuit {} gave stddev upper bound {} " - "while unmitigated stddev maximum is {}".format( - mitigator, - circuit_name, - mitigated_stddev_upper_bound, - max_unmitigated_stddev, - ), + f"Mitigator {mitigator} on circuit {circuit_name} gave stddev upper bound " + f"{mitigated_stddev_upper_bound} while unmitigated stddev maximum is " + f"{max_unmitigated_stddev}", ) def test_expectation_improvement(self): @@ -190,22 +184,15 @@ def test_expectation_improvement(self): self.assertLess( mitigated_error, unmitigated_error, - "Mitigator {} did not improve circuit {} expectation computation for diagonal {} " - "ideal: {}, unmitigated: {} mitigated: {}".format( - mitigator, - circuit_name, - diagonal, - ideal_expectation, - unmitigated_expectation, - mitigated_expectation, - ), + f"Mitigator {mitigator} did not improve circuit {circuit_name} expectation " + f"computation for diagonal {diagonal} ideal: {ideal_expectation}, unmitigated:" + f" {unmitigated_expectation} mitigated: {mitigated_expectation}", ) self.assertGreaterEqual( mitigated_stddev, unmitigated_stddev, - "Mitigator {} did not increase circuit {} the standard deviation".format( - mitigator, circuit_name - ), + f"Mitigator {mitigator} did not increase circuit {circuit_name} the" + f" standard deviation", ) def test_clbits_parameter(self): @@ -228,7 +215,7 @@ def test_clbits_parameter(self): self.assertLess( mitigated_error, 0.001, - "Mitigator {} did not correctly marganalize for qubits 1,2".format(mitigator), + f"Mitigator {mitigator} did not correctly marganalize for qubits 1,2", ) mitigated_probs_02 = ( @@ -240,7 +227,7 @@ def test_clbits_parameter(self): self.assertLess( mitigated_error, 0.001, - "Mitigator {} did not correctly marganalize for qubits 0,2".format(mitigator), + f"Mitigator {mitigator} did not correctly marganalize for qubits 0,2", ) def test_qubits_parameter(self): @@ -264,7 +251,7 @@ def test_qubits_parameter(self): self.assertLess( mitigated_error, 0.001, - "Mitigator {} did not correctly handle qubit order 0, 1, 2".format(mitigator), + f"Mitigator {mitigator} did not correctly handle qubit order 0, 1, 2", ) mitigated_probs_210 = ( @@ -276,7 +263,7 @@ def test_qubits_parameter(self): self.assertLess( mitigated_error, 0.001, - "Mitigator {} did not correctly handle qubit order 2, 1, 0".format(mitigator), + f"Mitigator {mitigator} did not correctly handle qubit order 2, 1, 0", ) mitigated_probs_102 = ( @@ -288,7 +275,7 @@ def test_qubits_parameter(self): self.assertLess( mitigated_error, 0.001, - "Mitigator {} did not correctly handle qubit order 1, 0, 2".format(mitigator), + "Mitigator {mitigator} did not correctly handle qubit order 1, 0, 2", ) def test_repeated_qubits_parameter(self): @@ -311,7 +298,7 @@ def test_repeated_qubits_parameter(self): self.assertLess( mitigated_error, 0.001, - "Mitigator {} did not correctly handle qubit order 2,1,0".format(mitigator), + f"Mitigator {mitigator} did not correctly handle qubit order 2,1,0", ) # checking qubit order 2,1,0 should not "overwrite" the default 0,1,2 @@ -324,9 +311,8 @@ def test_repeated_qubits_parameter(self): self.assertLess( mitigated_error, 0.001, - "Mitigator {} did not correctly handle qubit order 0,1,2 (the expected default)".format( - mitigator - ), + f"Mitigator {mitigator} did not correctly handle qubit order 0,1,2 " + f"(the expected default)", ) def test_qubits_subset_parameter(self): @@ -350,7 +336,7 @@ def test_qubits_subset_parameter(self): self.assertLess( mitigated_error, 0.001, - "Mitigator {} did not correctly handle qubit subset".format(mitigator), + "Mitigator {mitigator} did not correctly handle qubit subset", ) mitigated_probs_6 = ( @@ -362,7 +348,7 @@ def test_qubits_subset_parameter(self): self.assertLess( mitigated_error, 0.001, - "Mitigator {} did not correctly handle qubit subset".format(mitigator), + f"Mitigator {mitigator} did not correctly handle qubit subset", ) diagonal = str2diag("ZZ") ideal_expectation = 0 @@ -373,7 +359,7 @@ def test_qubits_subset_parameter(self): self.assertLess( mitigated_error, 0.1, - "Mitigator {} did not improve circuit expectation".format(mitigator), + f"Mitigator {mitigator} did not improve circuit expectation", ) def test_from_backend(self): diff --git a/test/python/synthesis/aqc/fast_gradient/test_layer1q.py b/test/python/synthesis/aqc/fast_gradient/test_layer1q.py index 43b164c42257..d2c5108391ff 100644 --- a/test/python/synthesis/aqc/fast_gradient/test_layer1q.py +++ b/test/python/synthesis/aqc/fast_gradient/test_layer1q.py @@ -62,7 +62,7 @@ def test_layer1q_matrix(self): # T == P^t @ G @ P. err = tut.relative_error(t_mat, iden[perm].T @ g_mat @ iden[perm]) - self.assertLess(err, eps, "err = {:0.16f}".format(err)) + self.assertLess(err, eps, f"err = {err:0.16f}") max_rel_err = max(max_rel_err, err) # Multiplication by permutation matrix of the left can be @@ -79,8 +79,7 @@ def test_layer1q_matrix(self): self.assertTrue( err1 < eps and err2 < eps and err3 < eps and err4 < eps, - "err1 = {:f}, err2 = {:f}, " - "err3 = {:f}, err4 = {:f}".format(err1, err2, err3, err4), + f"err1 = {err1:f}, err2 = {err2:f}, " f"err3 = {err3:f}, err4 = {err4:f}", ) max_rel_err = max(max_rel_err, err1, err2, err3, err4) @@ -128,12 +127,12 @@ def test_pmatrix_class(self): alt_ttmtt = pmat.finalize(temp_mat=tmp1) err1 = tut.relative_error(alt_ttmtt, ttmtt) - self.assertLess(err1, _eps, "relative error: {:f}".format(err1)) + self.assertLess(err1, _eps, f"relative error: {err1:f}") prod = np.complex128(np.trace(ttmtt @ t4)) alt_prod = pmat.product_q1(layer=c4, tmp1=tmp1, tmp2=tmp2) err2 = abs(alt_prod - prod) / abs(prod) - self.assertLess(err2, _eps, "relative error: {:f}".format(err2)) + self.assertLess(err2, _eps, f"relative error: {err2:f}") max_rel_err = max(max_rel_err, err1, err2) diff --git a/test/python/synthesis/aqc/fast_gradient/test_layer2q.py b/test/python/synthesis/aqc/fast_gradient/test_layer2q.py index 9de1e13df2d0..8f5655d6057e 100644 --- a/test/python/synthesis/aqc/fast_gradient/test_layer2q.py +++ b/test/python/synthesis/aqc/fast_gradient/test_layer2q.py @@ -65,7 +65,7 @@ def test_layer2q_matrix(self): # T == P^t @ G @ P. err = tut.relative_error(t_mat, iden[perm].T @ g_mat @ iden[perm]) - self.assertLess(err, _eps, "err = {:0.16f}".format(err)) + self.assertLess(err, _eps, f"err = {err:0.16f}") max_rel_err = max(max_rel_err, err) # Multiplication by permutation matrix of the left can be @@ -82,8 +82,8 @@ def test_layer2q_matrix(self): self.assertTrue( err1 < _eps and err2 < _eps and err3 < _eps and err4 < _eps, - "err1 = {:f}, err2 = {:f}, " - "err3 = {:f}, err4 = {:f}".format(err1, err2, err3, err4), + f"err1 = {err1:f}, err2 = {err2:f}, " + f"err3 = {err3:f}, err4 = {err4:f}", ) max_rel_err = max(max_rel_err, err1, err2, err3, err4) @@ -136,12 +136,12 @@ def test_pmatrix_class(self): alt_ttmtt = pmat.finalize(temp_mat=tmp1) err1 = tut.relative_error(alt_ttmtt, ttmtt) - self.assertLess(err1, _eps, "relative error: {:f}".format(err1)) + self.assertLess(err1, _eps, f"relative error: {err1:f}") prod = np.complex128(np.trace(ttmtt @ t4)) alt_prod = pmat.product_q2(layer=c4, tmp1=tmp1, tmp2=tmp2) err2 = abs(alt_prod - prod) / abs(prod) - self.assertLess(err2, _eps, "relative error: {:f}".format(err2)) + self.assertLess(err2, _eps, f"relative error: {err2:f}") max_rel_err = max(max_rel_err, err1, err2) diff --git a/test/python/synthesis/test_permutation_synthesis.py b/test/python/synthesis/test_permutation_synthesis.py index a879d5251f90..050df5a3fe1c 100644 --- a/test/python/synthesis/test_permutation_synthesis.py +++ b/test/python/synthesis/test_permutation_synthesis.py @@ -78,17 +78,13 @@ def test_invalid_permutations(self, width): pattern_out_of_range[0] = width with self.assertRaises(ValueError) as exc: _validate_permutation(pattern_out_of_range) - self.assertIn( - "input has length {0} and contains {0}".format(width), str(exc.exception) - ) + self.assertIn(f"input has length {width} and contains {width}", str(exc.exception)) pattern_duplicate = np.copy(pattern) pattern_duplicate[-1] = pattern[0] with self.assertRaises(ValueError) as exc: _validate_permutation(pattern_duplicate) - self.assertIn( - "input contains {} more than once".format(pattern[0]), str(exc.exception) - ) + self.assertIn(f"input contains {pattern[0]} more than once", str(exc.exception)) @data(4, 5, 10, 15, 20) def test_synth_permutation_basic(self, width): diff --git a/test/python/test_user_config.py b/test/python/test_user_config.py index ecc4ffaaa966..5b63462963c2 100644 --- a/test/python/test_user_config.py +++ b/test/python/test_user_config.py @@ -25,7 +25,7 @@ class TestUserConfig(QiskitTestCase): def setUp(self): super().setUp() - self.file_path = "test_%s.conf" % uuid4() + self.file_path = f"test_{uuid4()}.conf" def test_empty_file_read(self): config = user_config.UserConfig(self.file_path) diff --git a/test/python/transpiler/test_pass_scheduler.py b/test/python/transpiler/test_pass_scheduler.py index 6d6026d6148e..12ba81c78a6c 100644 --- a/test/python/transpiler/test_pass_scheduler.py +++ b/test/python/transpiler/test_pass_scheduler.py @@ -703,7 +703,7 @@ def assertPassLog(self, passmanager, list_of_passes): output_lines = self.output.readlines() pass_log_lines = [x for x in output_lines if x.startswith("Pass:")] for index, pass_name in enumerate(list_of_passes): - self.assertTrue(pass_log_lines[index].startswith("Pass: %s -" % pass_name)) + self.assertTrue(pass_log_lines[index].startswith(f"Pass: {pass_name} -")) def test_passes(self): """Dump passes in different FlowControllerLinear""" diff --git a/test/python/visualization/timeline/test_generators.py b/test/python/visualization/timeline/test_generators.py index 66afe3556b3d..5554248089ed 100644 --- a/test/python/visualization/timeline/test_generators.py +++ b/test/python/visualization/timeline/test_generators.py @@ -109,9 +109,7 @@ def test_gen_full_gate_name_with_finite_duration(self): self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3(0.00, 0.00, 0.00)[20]") - ref_latex = "{name}(0.00, 0.00, 0.00)[20]".format( - name=self.formatter["latex_symbol.gates"]["u3"] - ) + ref_latex = f"{self.formatter['latex_symbol.gates']['u3']}(0.00, 0.00, 0.00)[20]" self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { @@ -132,7 +130,7 @@ def test_gen_full_gate_name_with_zero_duration(self): self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1(0.00)") - ref_latex = "{name}(0.00)".format(name=self.formatter["latex_symbol.gates"]["u1"]) + ref_latex = f"{self.formatter['latex_symbol.gates']['u1']}(0.00)" self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { @@ -159,7 +157,7 @@ def test_gen_short_gate_name_with_finite_duration(self): self.assertListEqual(list(drawing_obj.yvals), [0.0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u3") - ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u3"]) + ref_latex = f"{self.formatter['latex_symbol.gates']['u3']}" self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { @@ -180,7 +178,7 @@ def test_gen_short_gate_name_with_zero_duration(self): self.assertListEqual(list(drawing_obj.yvals), [self.formatter["label_offset.frame_change"]]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "u1") - ref_latex = "{name}".format(name=self.formatter["latex_symbol.gates"]["u1"]) + ref_latex = f"{self.formatter['latex_symbol.gates']['u1']}" self.assertEqual(drawing_obj.latex, ref_latex) ref_styles = { @@ -250,6 +248,7 @@ def test_gen_bit_name(self): self.assertListEqual(list(drawing_obj.yvals), [0]) self.assertListEqual(drawing_obj.bits, [self.qubit]) self.assertEqual(drawing_obj.text, "bar") + # pylint: disable-next=consider-using-f-string ref_latex = r"{{\rm {register}}}_{{{index}}}".format(register="q", index="0") self.assertEqual(drawing_obj.latex, ref_latex) diff --git a/test/randomized/test_transpiler_equivalence.py b/test/randomized/test_transpiler_equivalence.py index 2dde71a5d39d..04dced90dfaa 100644 --- a/test/randomized/test_transpiler_equivalence.py +++ b/test/randomized/test_transpiler_equivalence.py @@ -306,10 +306,9 @@ def equivalent_transpile(self, kwargs): count_differences = dicts_almost_equal(aer_counts, xpiled_aer_counts, 0.05 * shots) - assert ( - count_differences == "" - ), "Counts not equivalent: {}\nFailing QASM Input:\n{}\n\nFailing QASM Output:\n{}".format( - count_differences, qasm2.dumps(self.qc), qasm2.dumps(xpiled_qc) + assert count_differences == "", ( + f"Counts not equivalent: {count_differences}\nFailing QASM Input:\n" + f"{qasm2.dumps(self.qc)}\n\nFailing QASM Output:\n{qasm2.dumps(xpiled_qc)}" ) diff --git a/test/utils/base.py b/test/utils/base.py index 747be7f66b51..63a8bf4384f0 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -81,10 +81,10 @@ def setUp(self): self.addTypeEqualityFunc(QuantumCircuit, self.assertQuantumCircuitEqual) if self.__setup_called: raise ValueError( - "In File: %s\n" + f"In File: {(sys.modules[self.__class__.__module__].__file__,)}\n" "TestCase.setUp was already called. Do not explicitly call " "setUp from your tests. In your own setUp, use super to call " - "the base setUp." % (sys.modules[self.__class__.__module__].__file__,) + "the base setUp." ) self.__setup_called = True @@ -92,10 +92,10 @@ def tearDown(self): super().tearDown() if self.__teardown_called: raise ValueError( - "In File: %s\n" + f"In File: {(sys.modules[self.__class__.__module__].__file__,)}\n" "TestCase.tearDown was already called. Do not explicitly call " "tearDown from your tests. In your own tearDown, use super to " - "call the base tearDown." % (sys.modules[self.__class__.__module__].__file__,) + "call the base tearDown." ) self.__teardown_called = True @@ -305,10 +305,10 @@ def valid_comparison(value): if places is not None: if delta is not None: raise TypeError("specify delta or places not both") - msg_suffix = " within %s places" % places + msg_suffix = f" within {places} places" else: delta = delta or 1e-8 - msg_suffix = " within %s delta" % delta + msg_suffix = f" within {delta} delta" # Compare all keys in both dicts, populating error_msg. error_msg = "" diff --git a/test/visual/results.py b/test/visual/results.py index efaf09bbbbfa..76fde794b394 100644 --- a/test/visual/results.py +++ b/test/visual/results.py @@ -83,30 +83,30 @@ def _new_gray(size, color): @staticmethod def passed_result_html(result, reference, diff, title): """Creates the html for passing tests""" - ret = '
%s ' % title + ret = f'
{title} ' ret += "" - ret += '
' % result - ret += '' % reference - ret += '' % diff + ret += f'
' + ret += f'' + ret += f'' ret += "
" return ret @staticmethod def failed_result_html(result, reference, diff, title): """Creates the html for failing tests""" - ret = '
%s ' % title + ret = f'
{title} ' ret += "" - ret += '
' % result - ret += '' % reference - ret += '' % diff + ret += f'
' + ret += f'' + ret += f'' ret += "
" return ret @staticmethod def no_reference_html(result, title): """Creates the html for missing-reference tests""" - ret = '
%s ' % title - ret += '" % (name, fullpath_name, fullpath_reference) + f'Download this image' + f" to {fullpath_reference}" + " and add/push to the repo" ) ret += Results.no_reference_html(fullpath_name, title) ret += "" diff --git a/tools/build_standard_commutations.py b/tools/build_standard_commutations.py index 56c452b11ce0..0e1fcdf1797d 100644 --- a/tools/build_standard_commutations.py +++ b/tools/build_standard_commutations.py @@ -143,12 +143,14 @@ def _dump_commuting_dict_as_python( dir_str = "standard_gates_commutations = {\n" for k, v in commutations.items(): if not isinstance(v, dict): + # pylint: disable-next=consider-using-f-string dir_str += ' ("{}", "{}"): {},\n'.format(*k, v) else: + # pylint: disable-next=consider-using-f-string dir_str += ' ("{}", "{}"): {{\n'.format(*k) for entry_key, entry_val in v.items(): - dir_str += " {}: {},\n".format(entry_key, entry_val) + dir_str += f" {entry_key}: {entry_val},\n" dir_str += " },\n" dir_str += "}\n" diff --git a/tools/find_stray_release_notes.py b/tools/find_stray_release_notes.py index 7e04f5ecc320..d694e0d89b8f 100755 --- a/tools/find_stray_release_notes.py +++ b/tools/find_stray_release_notes.py @@ -49,7 +49,7 @@ def _main(): failed_files = [x for x in res if x is not None] if len(failed_files) > 0: for failed_file in failed_files: - sys.stderr.write("%s is not in the correct location.\n" % failed_file) + sys.stderr.write(f"{failed_file} is not in the correct location.\n") sys.exit(1) sys.exit(0) diff --git a/tools/verify_headers.py b/tools/verify_headers.py index 7bd7d2bad4e7..552372b7725a 100755 --- a/tools/verify_headers.py +++ b/tools/verify_headers.py @@ -88,18 +88,18 @@ def validate_header(file_path): break if file_path.endswith(".rs"): if "".join(lines[start : start + 2]) != header_rs: - return (file_path, False, "Header up to copyright line does not match: %s" % header) + return (file_path, False, f"Header up to copyright line does not match: {header}") if not copyright_line.search(lines[start + 2]): return (file_path, False, "Header copyright line not found") if "".join(lines[start + 3 : start + 11]) != apache_text_rs: - return (file_path, False, "Header apache text string doesn't match:\n %s" % apache_text) + return (file_path, False, f"Header apache text string doesn't match:\n {apache_text}") else: if "".join(lines[start : start + 2]) != header: - return (file_path, False, "Header up to copyright line does not match: %s" % header) + return (file_path, False, f"Header up to copyright line does not match: {header}") if not copyright_line.search(lines[start + 2]): return (file_path, False, "Header copyright line not found") if "".join(lines[start + 3 : start + 11]) != apache_text: - return (file_path, False, "Header apache text string doesn't match:\n %s" % apache_text) + return (file_path, False, f"Header apache text string doesn't match:\n {apache_text}") return (file_path, True, None) @@ -122,8 +122,8 @@ def _main(): failed_files = [x for x in res if x[1] is False] if len(failed_files) > 0: for failed_file in failed_files: - sys.stderr.write("%s failed header check because:\n" % failed_file[0]) - sys.stderr.write("%s\n\n" % failed_file[2]) + sys.stderr.write(f"{failed_file[0]} failed header check because:\n") + sys.stderr.write(f"{failed_file[2]}\n\n") sys.exit(1) sys.exit(0)
' % result + ret = f'
{title} ' + ret += f'
' ret += "
" return ret @@ -119,11 +119,7 @@ def diff_images(self): if os.path.exists(os.path.join(SWD, fullpath_reference)): ratio, diff_name = Results._similarity_ratio(fullpath_name, fullpath_reference) - title = "{} | {} | ratio: {}".format( - name, - self.data[name]["testname"], - ratio, - ) + title = f"{name} | {self.data[name]['testname']} | ratio: {ratio}" if ratio == 1: self.exact_match.append(fullpath_name) else: @@ -158,8 +154,9 @@ def _repr_html_(self): ) else: title = ( - 'Download this image to %s' - " and add/push to the repo