Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove consider-using-f-string lint rule and updates #12423

Merged
merged 17 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions qiskit/assembler/assemble_circuits.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
17 changes: 5 additions & 12 deletions qiskit/assembler/assemble_schedules.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Expand Down Expand Up @@ -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]}"
)


Expand Down
2 changes: 1 addition & 1 deletion qiskit/assembler/disassemble.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]:
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/classicalfunction/boolean_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand Down
10 changes: 5 additions & 5 deletions qiskit/circuit/classicalfunction/classical_function_visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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):
Expand All @@ -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"""
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/classicalfunction/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/classicalregister.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)


Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/delay.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions qiskit/circuit/duration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 5 additions & 7 deletions qiskit/circuit/equivalence.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -273,19 +273,17 @@ 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}."
)


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."
)


Expand Down
4 changes: 2 additions & 2 deletions qiskit/circuit/gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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"""
Expand Down
9 changes: 5 additions & 4 deletions qiskit/circuit/instruction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/library/arithmetic/piecewise_chebyshev.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 7 additions & 7 deletions qiskit/circuit/library/data_preparation/state_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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, []

Expand All @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/library/graph_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did not realize the circuit name for GraphState was embedding a string representation of the adjacency matrix. Lol, that could be quite the string.


circuit.h(range(num_qubits))
for i in range(num_qubits):
Expand Down
3 changes: 1 addition & 2 deletions qiskit/circuit/library/hamiltonian_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/library/hidden_linear_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
5 changes: 2 additions & 3 deletions qiskit/circuit/library/n_local/n_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
14 changes: 6 additions & 8 deletions qiskit/circuit/library/n_local/qaoa_ansatz.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 2 additions & 4 deletions qiskit/circuit/library/overlap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
)
2 changes: 1 addition & 1 deletion qiskit/circuit/library/standard_gates/u3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading