Skip to content

Commit

Permalink
Update pylint version (#2158)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
chriseclectic committed May 31, 2024
1 parent 33f77c5 commit 9bfd110
Show file tree
Hide file tree
Showing 18 changed files with 57 additions and 93 deletions.
40 changes: 1 addition & 39 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ enable=use-symbolic-message-instead
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
disable=spelling, # way too noisy
no-self-use, # disabled as it is too verbose
fixme, # disabled as TODOs would show up as warnings
protected-access, # disabled as we don't follow the public vs private
# convention strictly
Expand All @@ -71,7 +70,6 @@ disable=spelling, # way too noisy
no-else-return, # relax "elif" after a clause with a return
docstring-first-line-empty, # relax docstring style
import-outside-toplevel,
bad-continuation, bad-whitespace, # differences of opinion with black
import-error, # overzealous with our optionals/dynamic packages
consider-using-f-string, # pass re-lint old commits
broad-exception-raised, # pass re-lint old commits
Expand Down Expand Up @@ -136,63 +134,33 @@ property-classes=abc.abstractproperty
# Regular expression matching correct module names
module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$

# Naming hint for module names
module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$

# Regular expression matching correct constant names
const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$

# Naming hint for constant names
const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$

# Regular expression matching correct class names
class-rgx=[A-Z_][a-zA-Z0-9]+$

# Naming hint for class names
class-name-hint=[A-Z_][a-zA-Z0-9]+$

# Regular expression matching correct function names
function-rgx=[a-z_][a-z0-9_]{2,30}$

# Naming hint for function names
function-name-hint=[a-z_][a-z0-9_]{2,30}$

# Regular expression matching correct method names
method-rgx=(([a-z_][a-z0-9_]{2,49})|(assert[A-Z][a-zA-Z0-9]{2,43})|(test_[_a-zA-Z0-9]{2,}))$

# Naming hint for method names
method-name-hint=[a-z_][a-z0-9_]{2,30}$ or camelCase `assert*` in tests.

# Regular expression matching correct attribute names
attr-rgx=[a-z_][a-z0-9_]{2,30}$

# Naming hint for attribute names
attr-name-hint=[a-z_][a-z0-9_]{2,30}$

# Regular expression matching correct argument names
argument-rgx=[a-z_][a-z0-9_]{2,30}|ax|dt$

# Naming hint for argument names
argument-name-hint=[a-z_][a-z0-9_]{2,30}$

# Regular expression matching correct variable names
variable-rgx=[a-z_][a-z0-9_]{1,30}$

# Naming hint for variable names
variable-name-hint=[a-z_][a-z0-9_]{1,30}$

# Regular expression matching correct class attribute names
class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$

# Naming hint for class attribute names
class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$

# Regular expression matching correct inline iteration names
inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$

# Naming hint for inline iteration names
inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$

# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
Expand Down Expand Up @@ -220,12 +188,6 @@ ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# else.
single-line-if-stmt=no

# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,dict-separator

# Maximum number of lines in a module
max-module-lines=1000

Expand Down Expand Up @@ -422,4 +384,4 @@ analyse-fallback-blocks=no

# Exceptions that will emit a warning when being caught. Defaults to
# "Exception"
overgeneral-exceptions=Exception
overgeneral-exceptions=builtins.Exception
4 changes: 2 additions & 2 deletions constraints.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pylint==2.4.4
astroid==2.3.3
pylint==2.16.2
astroid==2.14.2

# Jinja2 3.1.0 is incompatible with sphinx and/or jupyter until they are updated
# to work with the new jinja version (the jinja maintainers aren't going to
Expand Down
10 changes: 6 additions & 4 deletions qiskit_aer/backends/aer_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,11 +421,13 @@ def _inline_switch_case_op(self, instruction, continue_label, break_label, paren
case_data = CaseData(
label=f"{switch_name}_{i}",
args_list=[
self._convert_jump_conditional(
(instruction.operation.target, switch_val), bit_map
(
self._convert_jump_conditional(
(instruction.operation.target, switch_val), bit_map
)
if switch_val != CASE_DEFAULT
else []
)
if switch_val != CASE_DEFAULT
else []
for switch_val in case[0]
],
bit_map={
Expand Down
2 changes: 1 addition & 1 deletion qiskit_aer/backends/aer_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -985,7 +985,7 @@ def _validate(self, qobj):
break
if no_data:
logger.warning(
'No measure or save instruction in circuit "%s": ' "results will be empty.",
'No measure or save instruction in circuit "%s": results will be empty.',
experiment.header.name,
)

Expand Down
6 changes: 3 additions & 3 deletions qiskit_aer/backends/aerbackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def _convert_binds(self, circuits, parameter_binds, idx_maps=None):
]
return parameterizations

# pylint: disable=arguments-differ
# pylint: disable=arguments-renamed
def run(self, circuits, validate=False, parameter_binds=None, **run_options):
"""Run circuits on the backend.
Expand Down Expand Up @@ -244,7 +244,7 @@ def run(self, circuits, validate=False, parameter_binds=None, **run_options):
)
else:
raise TypeError(
"bad input to run() function;" "circuits must be either circuits or schedules"
"bad input to run() function; circuits must be either circuits or schedules"
)

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

for circ_id, aer_circuit in enumerate(aer_circuits):
Expand Down
2 changes: 1 addition & 1 deletion qiskit_aer/backends/qasm_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,7 @@ def _validate(self, qobj):
# Print warning if clbits but no measure
if no_measure:
logger.warning(
'No measurements in circuit "%s": ' "count data will return all zeros.",
'No measurements in circuit "%s": count data will return all zeros.',
experiment.header.name,
)

Expand Down
2 changes: 1 addition & 1 deletion qiskit_aer/backends/statevector_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ def _validate(self, qobj):
exp_name = experiment.header.name
if getattr(experiment.config, "shots", 1) != 1:
logger.info(
'"%s" only supports 1 shot. ' 'Setting shots=1 for circuit "%s".',
'"%s" only supports 1 shot. Setting shots=1 for circuit "%s".',
name,
exp_name,
)
Expand Down
2 changes: 1 addition & 1 deletion qiskit_aer/backends/unitary_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ def _validate(self, qobj):
exp_name = experiment.header.name
if getattr(experiment.config, "shots", 1) != 1:
logger.info(
'"%s" only supports 1 shot. ' 'Setting shots=1 for circuit "%s".',
'"%s" only supports 1 shot. Setting shots=1 for circuit "%s".',
name,
exp_name,
)
Expand Down
4 changes: 2 additions & 2 deletions qiskit_aer/jobs/aerjobset.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,10 +219,10 @@ def _get_worker_result(self, worker: int, timeout: Optional[float] = None):
logger.warning("AerJobSet %s Error: %s", aer_job.name(), result.header)
else:
logger.warning("AerJobSet %s did not return a result", aer_job.name())
except JobError:
except JobError as ex:
raise JobError(
"Timeout while waiting for the results of experiment {}".format(aer_job.name())
)
) from ex

if timeout:
timeout = original_timeout - (time.time() - start_time)
Expand Down
2 changes: 1 addition & 1 deletion qiskit_aer/noise/errors/quantum_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def _to_circuit(cls, op):
)
if isinstance(op, list):
if all(isinstance(aop, tuple) for aop in op):
num_qubits = max([max(qubits) for _, qubits in op]) + 1
num_qubits = max(max(qubits) for _, qubits in op) + 1
circ = QuantumCircuit(num_qubits)
for inst, qubits in op:
try:
Expand Down
39 changes: 19 additions & 20 deletions qiskit_aer/noise/noise_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,14 @@ class AerJSONEncoder(json.JSONEncoder):
"""

# pylint: disable=method-hidden,arguments-differ
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, complex):
return [obj.real, obj.imag]
if hasattr(obj, "to_dict"):
return obj.to_dict()
return super().default(obj)
def default(self, o):
if isinstance(o, np.ndarray):
return o.tolist()
if isinstance(o, complex):
return [o.real, o.imag]
if hasattr(o, "to_dict"):
return o.to_dict()
return super().default(o)


class QuantumErrorLocation(Instruction):
Expand Down Expand Up @@ -638,7 +638,7 @@ def __eq__(self, other):

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

def add_basis_gates(self, instructions):
"""Add additional gates to the noise model basis_gates.
Expand Down Expand Up @@ -975,7 +975,7 @@ def from_dict(noise_dict):
)

def inst_dic_list_to_circuit(dic_list):
num_qubits = max([max(dic["qubits"]) for dic in dic_list]) + 1
num_qubits = max(max(dic["qubits"]) for dic in dic_list) + 1
circ = QuantumCircuit(num_qubits)
for dic in dic_list:
if dic["name"] == "reset":
Expand Down Expand Up @@ -1113,8 +1113,8 @@ def _readout_errors_equal(self, other):
# Check local readout errors are equal
if sorted(self._local_readout_errors.keys()) != sorted(other._local_readout_errors.keys()):
return False
for key in self._local_readout_errors:
if self._local_readout_errors[key] != other._local_readout_errors[key]:
for key, value in self._local_readout_errors.items():
if value != other._local_readout_errors[key]:
return False
return True

Expand All @@ -1124,24 +1124,23 @@ def _all_qubit_quantum_errors_equal(self, other):
other._default_quantum_errors.keys()
):
return False
for key in self._default_quantum_errors:
if self._default_quantum_errors[key] != other._default_quantum_errors[key]:
for key, value in self._default_quantum_errors.items():
if value != other._default_quantum_errors[key]:
return False
return True

def _local_quantum_errors_equal(self, other):
"""Check two noise models have equal local quantum errors"""
if sorted(self._local_quantum_errors.keys()) != sorted(other._local_quantum_errors.keys()):
return False
for key in self._local_quantum_errors:
inner_dict1 = self._local_quantum_errors[key]
for key, value in self._local_quantum_errors.items():
inner_dict2 = other._local_quantum_errors[key]
if sorted(inner_dict1.keys()) != sorted(inner_dict2.keys()):
if sorted(value.keys()) != sorted(inner_dict2.keys()):
return False
for inner_key in inner_dict1:
if inner_dict1[inner_key] != inner_dict2[inner_key]:
for inner_key, inner_value in value.items():
if inner_value != inner_dict2[inner_key]:
return False
if self._local_quantum_errors[key] != other._local_quantum_errors[key]:
if value != other._local_quantum_errors[key]:
return False
return True

Expand Down
4 changes: 2 additions & 2 deletions qiskit_aer/primitives/estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def _compute(self, circuits, observables, parameter_values, run_options):
# Group and create measurement circuit
for circ_ind, obs_indices in circ_obs_map.items():
pauli_list = sum(
[self._observables[obs_ind].paulis for obs_ind in obs_indices]
self._observables[obs_ind].paulis for obs_ind in obs_indices
).unique()
if self._abelian_grouping:
pauli_lists = pauli_list.group_commuting(qubit_wise=True)
Expand Down Expand Up @@ -284,7 +284,7 @@ def _compute(self, circuits, observables, parameter_values, run_options):
if experiments:
results = (
self._backend.run(
circuits=experiments,
experiments,
parameter_binds=parameter_binds if any(parameter_binds) else None,
**run_options,
)
Expand Down
15 changes: 8 additions & 7 deletions qiskit_aer/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,18 @@ def _minimal_ext_cmd(cmd):
env["LANGUAGE"] = "C"
env["LANG"] = "C"
env["LC_ALL"] = "C"
proc = subprocess.Popen(
with subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
cwd=os.path.join(os.path.dirname(ROOT_DIR)),
)
out = proc.communicate()[0]
if proc.returncode > 0:
raise OSError
return out
encoding="utf-8",
) as proc:
out = proc.communicate()[0]
if proc.returncode > 0:
raise OSError
return out


def git_version():
Expand All @@ -56,7 +57,7 @@ def git_version():
return git_revision


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


Expand Down
2 changes: 1 addition & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ scikit-build>=0.11.0
asv
cvxpy>=1.0.0,<1.1.15;platform_system != 'Windows' and python_version < '3.11'
pylint
black[jupyter]~=23.0
black[jupyter]~=24.1
clang-format~=15.0.7
Sphinx>=1.8.3
jupyter-sphinx
Expand Down
8 changes: 5 additions & 3 deletions test/terra/backends/aer_simulator/test_fusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,9 +504,11 @@ def test_fusion_two_qubits(self):
self.assertTrue(
len(meta_enabled["output_ops"])
if "output_ops" in meta_enabled
else len(circuit.ops) < len(meta_disabled["output_ops"])
if "output_ops" in meta_disabled
else len(circuit.ops)
else (
len(circuit.ops) < len(meta_disabled["output_ops"])
if "output_ops" in meta_disabled
else len(circuit.ops)
)
)

def test_fusion_diagonal(self):
Expand Down
3 changes: 1 addition & 2 deletions test/terra/states/test_aer_densitymatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,7 @@ def test_two_qubit_QV(self):
state = AerDensityMatrix(QuantumVolume(2, seed=1111))
state.seed(1111)
counts = state.sample_counts(shots=1024)
self.assertEqual(4, len(counts))
self.assertTrue("00" in counts)
self.assertEqual(sum(counts.values()), 1024)

def test_evolve(self):
"""Test evolve method for circuits"""
Expand Down
3 changes: 1 addition & 2 deletions test/terra/states/test_aer_statevector.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,7 @@ def test_two_qubit_QV(self):
"""Test two qubit QuantumVolume"""
state = AerStatevector(QuantumVolume(2))
counts = state.sample_counts(shots=1024)
self.assertEqual(4, len(counts))
self.assertTrue("00" in counts)
self.assertEqual(sum(counts.values()), 1024)

def test_evolve(self):
"""Test method and device properties"""
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tox]
minversion = 2.1
minversion = 4.0
envlist = py38, py39, py310, py311, py312, lint
skipsdist = True

Expand Down

0 comments on commit 9bfd110

Please sign in to comment.