Skip to content

Commit 9bfd110

Browse files
Update pylint version (#2158)
* Update pylint version Updates pylint version and fixes linting errors and pylint config with updated version. * Add pylint disable rather than change arg name * Fix tests * fix typo
1 parent 33f77c5 commit 9bfd110

18 files changed

+57
-93
lines changed

.pylintrc

+1-39
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,6 @@ enable=use-symbolic-message-instead
5757
# no Warning level messages displayed, use"--disable=all --enable=classes
5858
# --disable=W"
5959
disable=spelling, # way too noisy
60-
no-self-use, # disabled as it is too verbose
6160
fixme, # disabled as TODOs would show up as warnings
6261
protected-access, # disabled as we don't follow the public vs private
6362
# convention strictly
@@ -71,7 +70,6 @@ disable=spelling, # way too noisy
7170
no-else-return, # relax "elif" after a clause with a return
7271
docstring-first-line-empty, # relax docstring style
7372
import-outside-toplevel,
74-
bad-continuation, bad-whitespace, # differences of opinion with black
7573
import-error, # overzealous with our optionals/dynamic packages
7674
consider-using-f-string, # pass re-lint old commits
7775
broad-exception-raised, # pass re-lint old commits
@@ -136,63 +134,33 @@ property-classes=abc.abstractproperty
136134
# Regular expression matching correct module names
137135
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
138136

139-
# Naming hint for module names
140-
module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
141-
142137
# Regular expression matching correct constant names
143138
const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
144139

145-
# Naming hint for constant names
146-
const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
147-
148140
# Regular expression matching correct class names
149141
class-rgx=[A-Z_][a-zA-Z0-9]+$
150142

151-
# Naming hint for class names
152-
class-name-hint=[A-Z_][a-zA-Z0-9]+$
153-
154143
# Regular expression matching correct function names
155144
function-rgx=[a-z_][a-z0-9_]{2,30}$
156145

157-
# Naming hint for function names
158-
function-name-hint=[a-z_][a-z0-9_]{2,30}$
159-
160146
# Regular expression matching correct method names
161147
method-rgx=(([a-z_][a-z0-9_]{2,49})|(assert[A-Z][a-zA-Z0-9]{2,43})|(test_[_a-zA-Z0-9]{2,}))$
162148

163-
# Naming hint for method names
164-
method-name-hint=[a-z_][a-z0-9_]{2,30}$ or camelCase `assert*` in tests.
165-
166149
# Regular expression matching correct attribute names
167150
attr-rgx=[a-z_][a-z0-9_]{2,30}$
168151

169-
# Naming hint for attribute names
170-
attr-name-hint=[a-z_][a-z0-9_]{2,30}$
171-
172152
# Regular expression matching correct argument names
173153
argument-rgx=[a-z_][a-z0-9_]{2,30}|ax|dt$
174154

175-
# Naming hint for argument names
176-
argument-name-hint=[a-z_][a-z0-9_]{2,30}$
177-
178155
# Regular expression matching correct variable names
179156
variable-rgx=[a-z_][a-z0-9_]{1,30}$
180157

181-
# Naming hint for variable names
182-
variable-name-hint=[a-z_][a-z0-9_]{1,30}$
183-
184158
# Regular expression matching correct class attribute names
185159
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
186160

187-
# Naming hint for class attribute names
188-
class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
189-
190161
# Regular expression matching correct inline iteration names
191162
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
192163

193-
# Naming hint for inline iteration names
194-
inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
195-
196164
# Regular expression which should only match function or class names that do
197165
# not require a docstring.
198166
no-docstring-rgx=^_
@@ -220,12 +188,6 @@ ignore-long-lines=^\s*(# )?<?https?://\S+>?$
220188
# else.
221189
single-line-if-stmt=no
222190

223-
# List of optional constructs for which whitespace checking is disabled. `dict-
224-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
225-
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
226-
# `empty-line` allows space-only lines.
227-
no-space-check=trailing-comma,dict-separator
228-
229191
# Maximum number of lines in a module
230192
max-module-lines=1000
231193

@@ -422,4 +384,4 @@ analyse-fallback-blocks=no
422384

423385
# Exceptions that will emit a warning when being caught. Defaults to
424386
# "Exception"
425-
overgeneral-exceptions=Exception
387+
overgeneral-exceptions=builtins.Exception

constraints.txt

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
pylint==2.4.4
2-
astroid==2.3.3
1+
pylint==2.16.2
2+
astroid==2.14.2
33

44
# Jinja2 3.1.0 is incompatible with sphinx and/or jupyter until they are updated
55
# to work with the new jinja version (the jinja maintainers aren't going to

qiskit_aer/backends/aer_compiler.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -421,11 +421,13 @@ def _inline_switch_case_op(self, instruction, continue_label, break_label, paren
421421
case_data = CaseData(
422422
label=f"{switch_name}_{i}",
423423
args_list=[
424-
self._convert_jump_conditional(
425-
(instruction.operation.target, switch_val), bit_map
424+
(
425+
self._convert_jump_conditional(
426+
(instruction.operation.target, switch_val), bit_map
427+
)
428+
if switch_val != CASE_DEFAULT
429+
else []
426430
)
427-
if switch_val != CASE_DEFAULT
428-
else []
429431
for switch_val in case[0]
430432
],
431433
bit_map={

qiskit_aer/backends/aer_simulator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -985,7 +985,7 @@ def _validate(self, qobj):
985985
break
986986
if no_data:
987987
logger.warning(
988-
'No measure or save instruction in circuit "%s": ' "results will be empty.",
988+
'No measure or save instruction in circuit "%s": results will be empty.',
989989
experiment.header.name,
990990
)
991991

qiskit_aer/backends/aerbackend.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ def _convert_binds(self, circuits, parameter_binds, idx_maps=None):
144144
]
145145
return parameterizations
146146

147-
# pylint: disable=arguments-differ
147+
# pylint: disable=arguments-renamed
148148
def run(self, circuits, validate=False, parameter_binds=None, **run_options):
149149
"""Run circuits on the backend.
150150
@@ -244,7 +244,7 @@ def run(self, circuits, validate=False, parameter_binds=None, **run_options):
244244
)
245245
else:
246246
raise TypeError(
247-
"bad input to run() function;" "circuits must be either circuits or schedules"
247+
"bad input to run() function; circuits must be either circuits or schedules"
248248
)
249249

250250
def _run_circuits(self, circuits, parameter_binds, **run_options):
@@ -458,7 +458,7 @@ def _execute_circuits_job(
458458
run_options["parameterizations"] = self._convert_binds(
459459
circuits, parameter_binds, idx_maps
460460
)
461-
elif not all([len(circuit.parameters) == 0 for circuit in circuits]):
461+
elif not all(len(circuit.parameters) == 0 for circuit in circuits):
462462
raise AerError("circuits have parameters but parameter_binds is not specified.")
463463

464464
for circ_id, aer_circuit in enumerate(aer_circuits):

qiskit_aer/backends/qasm_simulator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -634,7 +634,7 @@ def _validate(self, qobj):
634634
# Print warning if clbits but no measure
635635
if no_measure:
636636
logger.warning(
637-
'No measurements in circuit "%s": ' "count data will return all zeros.",
637+
'No measurements in circuit "%s": count data will return all zeros.',
638638
experiment.header.name,
639639
)
640640

qiskit_aer/backends/statevector_simulator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,7 @@ def _validate(self, qobj):
375375
exp_name = experiment.header.name
376376
if getattr(experiment.config, "shots", 1) != 1:
377377
logger.info(
378-
'"%s" only supports 1 shot. ' 'Setting shots=1 for circuit "%s".',
378+
'"%s" only supports 1 shot. Setting shots=1 for circuit "%s".',
379379
name,
380380
exp_name,
381381
)

qiskit_aer/backends/unitary_simulator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ def _validate(self, qobj):
360360
exp_name = experiment.header.name
361361
if getattr(experiment.config, "shots", 1) != 1:
362362
logger.info(
363-
'"%s" only supports 1 shot. ' 'Setting shots=1 for circuit "%s".',
363+
'"%s" only supports 1 shot. Setting shots=1 for circuit "%s".',
364364
name,
365365
exp_name,
366366
)

qiskit_aer/jobs/aerjobset.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -219,10 +219,10 @@ def _get_worker_result(self, worker: int, timeout: Optional[float] = None):
219219
logger.warning("AerJobSet %s Error: %s", aer_job.name(), result.header)
220220
else:
221221
logger.warning("AerJobSet %s did not return a result", aer_job.name())
222-
except JobError:
222+
except JobError as ex:
223223
raise JobError(
224224
"Timeout while waiting for the results of experiment {}".format(aer_job.name())
225-
)
225+
) from ex
226226

227227
if timeout:
228228
timeout = original_timeout - (time.time() - start_time)

qiskit_aer/noise/errors/quantum_error.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ def _to_circuit(cls, op):
194194
)
195195
if isinstance(op, list):
196196
if all(isinstance(aop, tuple) for aop in op):
197-
num_qubits = max([max(qubits) for _, qubits in op]) + 1
197+
num_qubits = max(max(qubits) for _, qubits in op) + 1
198198
circ = QuantumCircuit(num_qubits)
199199
for inst, qubits in op:
200200
try:

qiskit_aer/noise/noise_model.py

+19-20
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,14 @@ class AerJSONEncoder(json.JSONEncoder):
5252
"""
5353

5454
# pylint: disable=method-hidden,arguments-differ
55-
def default(self, obj):
56-
if isinstance(obj, np.ndarray):
57-
return obj.tolist()
58-
if isinstance(obj, complex):
59-
return [obj.real, obj.imag]
60-
if hasattr(obj, "to_dict"):
61-
return obj.to_dict()
62-
return super().default(obj)
55+
def default(self, o):
56+
if isinstance(o, np.ndarray):
57+
return o.tolist()
58+
if isinstance(o, complex):
59+
return [o.real, o.imag]
60+
if hasattr(o, "to_dict"):
61+
return o.to_dict()
62+
return super().default(o)
6363

6464

6565
class QuantumErrorLocation(Instruction):
@@ -638,7 +638,7 @@ def __eq__(self, other):
638638

639639
def reset(self):
640640
"""Reset the noise model."""
641-
self.__init__()
641+
self.__init__() # pylint: disable = unnecessary-dunder-call
642642

643643
def add_basis_gates(self, instructions):
644644
"""Add additional gates to the noise model basis_gates.
@@ -975,7 +975,7 @@ def from_dict(noise_dict):
975975
)
976976

977977
def inst_dic_list_to_circuit(dic_list):
978-
num_qubits = max([max(dic["qubits"]) for dic in dic_list]) + 1
978+
num_qubits = max(max(dic["qubits"]) for dic in dic_list) + 1
979979
circ = QuantumCircuit(num_qubits)
980980
for dic in dic_list:
981981
if dic["name"] == "reset":
@@ -1113,8 +1113,8 @@ def _readout_errors_equal(self, other):
11131113
# Check local readout errors are equal
11141114
if sorted(self._local_readout_errors.keys()) != sorted(other._local_readout_errors.keys()):
11151115
return False
1116-
for key in self._local_readout_errors:
1117-
if self._local_readout_errors[key] != other._local_readout_errors[key]:
1116+
for key, value in self._local_readout_errors.items():
1117+
if value != other._local_readout_errors[key]:
11181118
return False
11191119
return True
11201120

@@ -1124,24 +1124,23 @@ def _all_qubit_quantum_errors_equal(self, other):
11241124
other._default_quantum_errors.keys()
11251125
):
11261126
return False
1127-
for key in self._default_quantum_errors:
1128-
if self._default_quantum_errors[key] != other._default_quantum_errors[key]:
1127+
for key, value in self._default_quantum_errors.items():
1128+
if value != other._default_quantum_errors[key]:
11291129
return False
11301130
return True
11311131

11321132
def _local_quantum_errors_equal(self, other):
11331133
"""Check two noise models have equal local quantum errors"""
11341134
if sorted(self._local_quantum_errors.keys()) != sorted(other._local_quantum_errors.keys()):
11351135
return False
1136-
for key in self._local_quantum_errors:
1137-
inner_dict1 = self._local_quantum_errors[key]
1136+
for key, value in self._local_quantum_errors.items():
11381137
inner_dict2 = other._local_quantum_errors[key]
1139-
if sorted(inner_dict1.keys()) != sorted(inner_dict2.keys()):
1138+
if sorted(value.keys()) != sorted(inner_dict2.keys()):
11401139
return False
1141-
for inner_key in inner_dict1:
1142-
if inner_dict1[inner_key] != inner_dict2[inner_key]:
1140+
for inner_key, inner_value in value.items():
1141+
if inner_value != inner_dict2[inner_key]:
11431142
return False
1144-
if self._local_quantum_errors[key] != other._local_quantum_errors[key]:
1143+
if value != other._local_quantum_errors[key]:
11451144
return False
11461145
return True
11471146

qiskit_aer/primitives/estimator.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ def _compute(self, circuits, observables, parameter_values, run_options):
244244
# Group and create measurement circuit
245245
for circ_ind, obs_indices in circ_obs_map.items():
246246
pauli_list = sum(
247-
[self._observables[obs_ind].paulis for obs_ind in obs_indices]
247+
self._observables[obs_ind].paulis for obs_ind in obs_indices
248248
).unique()
249249
if self._abelian_grouping:
250250
pauli_lists = pauli_list.group_commuting(qubit_wise=True)
@@ -284,7 +284,7 @@ def _compute(self, circuits, observables, parameter_values, run_options):
284284
if experiments:
285285
results = (
286286
self._backend.run(
287-
circuits=experiments,
287+
experiments,
288288
parameter_binds=parameter_binds if any(parameter_binds) else None,
289289
**run_options,
290290
)

qiskit_aer/version.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -31,17 +31,18 @@ def _minimal_ext_cmd(cmd):
3131
env["LANGUAGE"] = "C"
3232
env["LANG"] = "C"
3333
env["LC_ALL"] = "C"
34-
proc = subprocess.Popen(
34+
with subprocess.Popen(
3535
cmd,
3636
stdout=subprocess.PIPE,
3737
stderr=subprocess.PIPE,
3838
env=env,
3939
cwd=os.path.join(os.path.dirname(ROOT_DIR)),
40-
)
41-
out = proc.communicate()[0]
42-
if proc.returncode > 0:
43-
raise OSError
44-
return out
40+
encoding="utf-8",
41+
) as proc:
42+
out = proc.communicate()[0]
43+
if proc.returncode > 0:
44+
raise OSError
45+
return out
4546

4647

4748
def git_version():
@@ -56,7 +57,7 @@ def git_version():
5657
return git_revision
5758

5859

59-
with open(os.path.join(ROOT_DIR, "VERSION.txt"), "r") as version_file:
60+
with open(os.path.join(ROOT_DIR, "VERSION.txt"), "r", encoding="utf-8") as version_file:
6061
VERSION = version_file.read().strip()
6162

6263

requirements-dev.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ scikit-build>=0.11.0
55
asv
66
cvxpy>=1.0.0,<1.1.15;platform_system != 'Windows' and python_version < '3.11'
77
pylint
8-
black[jupyter]~=23.0
8+
black[jupyter]~=24.1
99
clang-format~=15.0.7
1010
Sphinx>=1.8.3
1111
jupyter-sphinx

test/terra/backends/aer_simulator/test_fusion.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -504,9 +504,11 @@ def test_fusion_two_qubits(self):
504504
self.assertTrue(
505505
len(meta_enabled["output_ops"])
506506
if "output_ops" in meta_enabled
507-
else len(circuit.ops) < len(meta_disabled["output_ops"])
508-
if "output_ops" in meta_disabled
509-
else len(circuit.ops)
507+
else (
508+
len(circuit.ops) < len(meta_disabled["output_ops"])
509+
if "output_ops" in meta_disabled
510+
else len(circuit.ops)
511+
)
510512
)
511513

512514
def test_fusion_diagonal(self):

test/terra/states/test_aer_densitymatrix.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,7 @@ def test_two_qubit_QV(self):
150150
state = AerDensityMatrix(QuantumVolume(2, seed=1111))
151151
state.seed(1111)
152152
counts = state.sample_counts(shots=1024)
153-
self.assertEqual(4, len(counts))
154-
self.assertTrue("00" in counts)
153+
self.assertEqual(sum(counts.values()), 1024)
155154

156155
def test_evolve(self):
157156
"""Test evolve method for circuits"""

test/terra/states/test_aer_statevector.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -157,8 +157,7 @@ def test_two_qubit_QV(self):
157157
"""Test two qubit QuantumVolume"""
158158
state = AerStatevector(QuantumVolume(2))
159159
counts = state.sample_counts(shots=1024)
160-
self.assertEqual(4, len(counts))
161-
self.assertTrue("00" in counts)
160+
self.assertEqual(sum(counts.values()), 1024)
162161

163162
def test_evolve(self):
164163
"""Test method and device properties"""

tox.ini

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[tox]
2-
minversion = 2.1
2+
minversion = 4.0
33
envlist = py38, py39, py310, py311, py312, lint
44
skipsdist = True
55

0 commit comments

Comments
 (0)