Skip to content

Commit 5d7b775

Browse files
1ucian0jakelishman
authored andcommitted
Fix the possibly-used-before-assignment in pylint (Qiskit#12542)
* fix the possibly-used-before-assignment in pylint * qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py * test.python.quantum_info.operators.test_utils * Apply suggestions from code review Co-authored-by: Jake Lishman <jake@binhbar.com> * https://github.com/Qiskit/qiskit/pull/12542/files#r1636214044 * RuntimeError * RuntimeError --------- Co-authored-by: Jake Lishman <jake@binhbar.com>
1 parent baac093 commit 5d7b775

24 files changed

+67
-41
lines changed

pyproject.toml

-1
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,6 @@ disable = [
221221
"consider-using-f-string",
222222
"no-member", # for dynamically created members
223223
"not-context-manager",
224-
"possibly-used-before-assignment",
225224
"unnecessary-lambda-assignment", # do not want to implement
226225
"unspecified-encoding", # do not want to implement
227226
]

qiskit/primitives/backend_estimator.py

+2
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ def _run_circuits(
6565
max_circuits = getattr(backend.configuration(), "max_experiments", None)
6666
elif isinstance(backend, BackendV2):
6767
max_circuits = backend.max_circuits
68+
else:
69+
raise RuntimeError("Backend version not supported")
6870
if max_circuits:
6971
jobs = [
7072
backend.run(circuits[pos : pos + max_circuits], **run_options)

qiskit/pulse/macros.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -124,8 +124,13 @@ def _measure_v1(
124124
for qubit in qubits:
125125
measure_groups.add(tuple(meas_map[qubit]))
126126
for measure_group_qubits in measure_groups:
127-
if qubit_mem_slots is not None:
128-
unused_mem_slots = set(measure_group_qubits) - set(qubit_mem_slots.values())
127+
128+
unused_mem_slots = (
129+
set()
130+
if qubit_mem_slots is None
131+
else set(measure_group_qubits) - set(qubit_mem_slots.values())
132+
)
133+
129134
try:
130135
default_sched = inst_map.get(measure_name, measure_group_qubits)
131136
except exceptions.PulseError as ex:

qiskit/qpy/binary_io/circuits.py

+1
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,7 @@ def _parse_custom_operation(
446446
) = custom_operations[gate_name]
447447
else:
448448
type_str, num_qubits, num_clbits, definition = custom_operations[gate_name]
449+
base_gate_raw = ctrl_state = num_ctrl_qubits = None
449450
# Strip the trailing "_{uuid}" from the gate name if the version >=11
450451
if version >= 11:
451452
gate_name = "_".join(gate_name.split("_")[:-1])

qiskit/quantum_info/operators/operator.py

+9-11
Original file line numberDiff line numberDiff line change
@@ -414,29 +414,27 @@ def from_circuit(
414414

415415
from qiskit.synthesis.permutation.permutation_utils import _inverse_pattern
416416

417+
op = Operator(circuit)
418+
417419
if initial_layout is not None:
418420
input_qubits = [None] * len(layout.input_qubit_mapping)
419421
for q, p in layout.input_qubit_mapping.items():
420422
input_qubits[p] = q
421423

422424
initial_permutation = initial_layout.to_permutation(input_qubits)
423425
initial_permutation_inverse = _inverse_pattern(initial_permutation)
426+
op = op.apply_permutation(initial_permutation, True)
424427

425-
if final_layout is not None:
428+
if final_layout is not None:
429+
final_permutation = final_layout.to_permutation(circuit.qubits)
430+
final_permutation_inverse = _inverse_pattern(final_permutation)
431+
op = op.apply_permutation(final_permutation_inverse, False)
432+
op = op.apply_permutation(initial_permutation_inverse, False)
433+
elif final_layout is not None:
426434
final_permutation = final_layout.to_permutation(circuit.qubits)
427435
final_permutation_inverse = _inverse_pattern(final_permutation)
428-
429-
op = Operator(circuit)
430-
431-
if initial_layout:
432-
op = op.apply_permutation(initial_permutation, True)
433-
434-
if final_layout:
435436
op = op.apply_permutation(final_permutation_inverse, False)
436437

437-
if initial_layout:
438-
op = op.apply_permutation(initial_permutation_inverse, False)
439-
440438
return op
441439

442440
def is_unitary(self, atol=None, rtol=None):

qiskit/quantum_info/operators/symplectic/sparse_pauli_op.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -135,19 +135,19 @@ def __init__(
135135

136136
pauli_list = PauliList(data.copy() if copy and hasattr(data, "copy") else data)
137137

138-
if isinstance(coeffs, np.ndarray):
139-
dtype = object if coeffs.dtype == object else complex
140-
elif coeffs is not None:
141-
if not isinstance(coeffs, (np.ndarray, Sequence)):
142-
coeffs = [coeffs]
143-
if any(isinstance(coeff, ParameterExpression) for coeff in coeffs):
144-
dtype = object
145-
else:
146-
dtype = complex
147-
148138
if coeffs is None:
149139
coeffs = np.ones(pauli_list.size, dtype=complex)
150140
else:
141+
if isinstance(coeffs, np.ndarray):
142+
dtype = object if coeffs.dtype == object else complex
143+
else:
144+
if not isinstance(coeffs, Sequence):
145+
coeffs = [coeffs]
146+
if any(isinstance(coeff, ParameterExpression) for coeff in coeffs):
147+
dtype = object
148+
else:
149+
dtype = complex
150+
151151
coeffs_asarray = np.asarray(coeffs, dtype=dtype)
152152
coeffs = (
153153
coeffs_asarray.copy()

qiskit/transpiler/passes/basis/unroll_custom_definitions.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,9 @@ def run(self, dag):
6060
if self._basis_gates is None and self._target is None:
6161
return dag
6262

63+
device_insts = {"measure", "reset", "barrier", "snapshot", "delay", "store"}
6364
if self._target is None:
64-
basic_insts = {"measure", "reset", "barrier", "snapshot", "delay", "store"}
65-
device_insts = basic_insts | set(self._basis_gates)
65+
device_insts |= set(self._basis_gates)
6666

6767
for node in dag.op_nodes():
6868
if isinstance(node.op, ControlFlowOp):
@@ -77,14 +77,14 @@ def run(self, dag):
7777

7878
controlled_gate_open_ctrl = isinstance(node.op, ControlledGate) and node.op._open_ctrl
7979
if not controlled_gate_open_ctrl:
80-
inst_supported = (
81-
self._target.instruction_supported(
80+
if self._target is not None:
81+
inst_supported = self._target.instruction_supported(
8282
operation_name=node.op.name,
8383
qargs=tuple(dag.find_bit(x).index for x in node.qargs),
8484
)
85-
if self._target is not None
86-
else node.name in device_insts
87-
)
85+
else:
86+
inst_supported = node.name in device_insts
87+
8888
if inst_supported or self._equiv_lib.has_entry(node.op):
8989
continue
9090
try:

qiskit/transpiler/passes/optimization/commutative_cancellation.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
import numpy as np
1717

1818
from qiskit.circuit.quantumregister import QuantumRegister
19-
from qiskit.transpiler.exceptions import TranspilerError
2019
from qiskit.transpiler.basepasses import TransformationPass
2120
from qiskit.transpiler.passmanager import PassManager
2221
from qiskit.transpiler.passes.optimization.commutation_analysis import CommutationAnalysis
@@ -72,9 +71,6 @@ def run(self, dag):
7271
7372
Returns:
7473
DAGCircuit: the optimized DAG.
75-
76-
Raises:
77-
TranspilerError: when the 1-qubit rotation gates are not found
7874
"""
7975
var_z_gate = None
8076
z_var_gates = [gate for gate in dag.count_ops().keys() if gate in self._var_z_map]
@@ -146,7 +142,7 @@ def run(self, dag):
146142
or len(current_node.qargs) != 1
147143
or current_node.qargs[0] != run_qarg
148144
):
149-
raise TranspilerError("internal error")
145+
raise RuntimeError("internal error")
150146

151147
if current_node.name in ["p", "u1", "rz", "rx"]:
152148
current_angle = float(current_node.op.params[0])
@@ -156,6 +152,10 @@ def run(self, dag):
156152
current_angle = np.pi / 4
157153
elif current_node.name == "s":
158154
current_angle = np.pi / 2
155+
else:
156+
raise RuntimeError(
157+
f"Angle for operation {current_node.name } is not defined"
158+
)
159159

160160
# Compose gates
161161
total_angle = current_angle + total_angle
@@ -167,6 +167,8 @@ def run(self, dag):
167167
new_op = var_z_gate(total_angle)
168168
elif cancel_set_key[0] == "x_rotation":
169169
new_op = RXGate(total_angle)
170+
else:
171+
raise RuntimeError("impossible case")
170172

171173
new_op_phase = 0
172174
if np.mod(total_angle, (2 * np.pi)) > _CUTOFF_PRECISION:

qiskit/visualization/circuit/matplotlib.py

+2
Original file line numberDiff line numberDiff line change
@@ -1584,6 +1584,8 @@ def _flow_op_gate(self, node, node_data, glob_data):
15841584
flow_text = " For"
15851585
elif isinstance(node.op, SwitchCaseOp):
15861586
flow_text = "Switch"
1587+
else:
1588+
flow_text = node.op.name
15871589

15881590
# Some spacers. op_spacer moves 'Switch' back a bit for alignment,
15891591
# expr_spacer moves the expr over to line up with 'Switch' and

test/benchmarks/randomized_benchmarking.py

+1
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ def clifford_2_qubit_circuit(num):
105105
qc = QuantumCircuit(2)
106106
if vals[0] == 0 or vals[0] == 3:
107107
(form, i0, i1, j0, j1, p0, p1) = vals
108+
k0, k1 = (None, None)
108109
else:
109110
(form, i0, i1, j0, j1, k0, k1, p0, p1) = vals
110111
if i0 == 1:

test/benchmarks/utils.py

+2
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,8 @@ def random_circuit(
126126
operation = rng.choice(two_q_ops)
127127
elif num_operands == 3:
128128
operation = rng.choice(three_q_ops)
129+
else:
130+
raise RuntimeError("not supported number of operands")
129131
if operation in one_param:
130132
num_angles = 1
131133
elif operation in two_param:

test/python/circuit/test_parameters.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1091,7 +1091,7 @@ def test_decompose_propagates_bound_parameters(self, target_type, parameter_type
10911091

10921092
if target_type == "gate":
10931093
inst = qc.to_gate()
1094-
elif target_type == "instruction":
1094+
else: # target_type == "instruction":
10951095
inst = qc.to_instruction()
10961096

10971097
qc2 = QuantumCircuit(1)
@@ -1132,7 +1132,7 @@ def test_decompose_propagates_deeply_bound_parameters(self, target_type, paramet
11321132

11331133
if target_type == "gate":
11341134
inst = qc1.to_gate()
1135-
elif target_type == "instruction":
1135+
else: # target_type == "instruction":
11361136
inst = qc1.to_instruction()
11371137

11381138
qc2 = QuantumCircuit(1)
@@ -1188,7 +1188,7 @@ def test_executing_parameterized_instruction_bound_early(self, target_type):
11881188

11891189
if target_type == "gate":
11901190
sub_inst = sub_qc.to_gate()
1191-
elif target_type == "instruction":
1191+
else: # target_type == "instruction":
11921192
sub_inst = sub_qc.to_instruction()
11931193

11941194
unbound_qc = QuantumCircuit(2, 1)
@@ -1405,6 +1405,7 @@ def _paramvec_names(prefix, length):
14051405

14061406
@ddt
14071407
class TestParameterExpressions(QiskitTestCase):
1408+
# pylint: disable=possibly-used-before-assignment
14081409
"""Test expressions of Parameters."""
14091410

14101411
# supported operations dictionary operation : accuracy (0=exact match)

test/python/classical_function_compiler/test_boolean_expression.py

+1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
2929
@ddt
3030
class TestBooleanExpression(QiskitTestCase):
31+
# pylint: disable=possibly-used-before-assignment
3132
"""Test boolean expression."""
3233

3334
@data(

test/python/classical_function_compiler/test_classical_function.py

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
2828
class TestOracleDecomposition(QiskitTestCase):
29+
# pylint: disable=possibly-used-before-assignment
2930
"""Tests ClassicalFunction.decomposition."""
3031

3132
def test_grover_oracle(self):

test/python/classical_function_compiler/test_parse.py

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
2727
class TestParseFail(QiskitTestCase):
28+
# pylint: disable=possibly-used-before-assignment
2829
"""Tests bad_examples with the classicalfunction parser."""
2930

3031
def assertExceptionMessage(self, context, message):

test/python/classical_function_compiler/test_simulate.py

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
2727
@ddt
2828
class TestSimulate(QiskitTestCase):
29+
# pylint: disable=possibly-used-before-assignment
2930
"""Tests LogicNetwork.simulate method"""
3031

3132
@data(*utils.example_list())

test/python/classical_function_compiler/test_synthesis.py

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
2828
class TestSynthesis(QiskitTestCase):
29+
# pylint: disable=possibly-used-before-assignment
2930
"""Tests ClassicalFunction.synth method."""
3031

3132
def test_grover_oracle(self):

test/python/classical_function_compiler/test_tweedledum2qiskit.py

+1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
3131
class TestTweedledum2Qiskit(QiskitTestCase):
32+
# pylint: disable=possibly-used-before-assignment
3233
"""Tests qiskit.transpiler.classicalfunction.utils.tweedledum2qiskit function."""
3334

3435
def test_x(self):

test/python/classical_function_compiler/test_typecheck.py

+2
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
2727
class TestTypeCheck(QiskitTestCase):
28+
# pylint: disable=possibly-used-before-assignment
2829
"""Tests classicalfunction compiler type checker (good examples)."""
2930

3031
def test_id(self):
@@ -74,6 +75,7 @@ def test_bool_or(self):
7475

7576
@unittest.skipUnless(HAS_TWEEDLEDUM, "Tweedledum is required for these tests.")
7677
class TestTypeCheckFail(QiskitTestCase):
78+
# pylint: disable=possibly-used-before-assignment
7779
"""Tests classicalfunction compiler type checker (bad examples)."""
7880

7981
def assertExceptionMessage(self, context, message):

test/python/visualization/test_circuit_drawer.py

+2
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ def test_default_output(self):
5555

5656
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "Skipped because matplotlib is not available")
5757
def test_mpl_config_with_path(self):
58+
# pylint: disable=possibly-used-before-assignment
5859
# It's too easy to get too nested in a test with many context managers.
5960
tempdir = tempfile.TemporaryDirectory() # pylint: disable=consider-using-with
6061
self.addCleanup(tempdir.cleanup)
@@ -128,6 +129,7 @@ def test_latex_unsupported_image_format_error_message(self):
128129

129130
@_latex_drawer_condition
130131
def test_latex_output_file_correct_format(self):
132+
# pylint: disable=possibly-used-before-assignment
131133
with patch("qiskit.user_config.get_config", return_value={"circuit_drawer": "latex"}):
132134
circuit = QuantumCircuit()
133135
filename = "file.gif"

test/python/visualization/test_circuit_text_drawer.py

+1
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ def test_text_no_pager(self):
185185

186186

187187
class TestTextDrawerGatesInCircuit(QiskitTestCase):
188+
# pylint: disable=possibly-used-before-assignment
188189
"""Gate by gate checks in different settings."""
189190

190191
def test_text_measure_cregbundle(self):

test/python/visualization/test_gate_map.py

+1
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
@unittest.skipUnless(optionals.HAS_PIL, "PIL not available")
4646
@unittest.skipUnless(optionals.HAS_SEABORN, "seaborn not available")
4747
class TestGateMap(QiskitVisualizationTestCase):
48+
# pylint: disable=possibly-used-before-assignment
4849
"""visual tests for plot_gate_map"""
4950

5051
backends = [Fake5QV1(), Fake20QV1(), Fake7QPulseV1()]

test/python/visualization/test_plot_histogram.py

+1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828

2929
@unittest.skipUnless(optionals.HAS_MATPLOTLIB, "matplotlib not available.")
3030
class TestPlotHistogram(QiskitVisualizationTestCase):
31+
# pylint: disable=possibly-used-before-assignment
3132
"""Qiskit plot_histogram tests."""
3233

3334
def test_different_counts_lengths(self):

tools/build_standard_commutations.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -102,12 +102,12 @@ def _generate_commutation_dict(considered_gates: List[Gate] = None) -> dict:
102102
commutation_relation = cc.commute(
103103
op1, qargs1, cargs1, op2, qargs2, cargs2, max_num_qubits=4
104104
)
105+
106+
gate_pair_commutation[relative_placement] = commutation_relation
105107
else:
106108
pass
107109
# TODO
108110

109-
gate_pair_commutation[relative_placement] = commutation_relation
110-
111111
commutations[gate0.name, gate1.name] = gate_pair_commutation
112112
return commutations
113113

0 commit comments

Comments
 (0)