Skip to content

Commit

Permalink
Update pylint version
Browse files Browse the repository at this point in the history
Updates pylint version and fixes linting errors and pylint config with updated version.
  • Loading branch information
chriseclectic committed May 30, 2024
1 parent 33f77c5 commit 2b2a1f3
Show file tree
Hide file tree
Showing 16 changed files with 65 additions and 99 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
28 changes: 14 additions & 14 deletions qiskit_aer/backends/aerbackend.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,11 @@ def _convert_binds(self, circuits, parameter_binds, idx_maps=None):
return parameterizations

# pylint: disable=arguments-differ
def run(self, circuits, validate=False, parameter_binds=None, **run_options):
def run(self, run_input, validate=False, parameter_binds=None, **run_options):
"""Run circuits on the backend.
Args:
circuits (QuantumCircuit or list): The QuantumCircuit (or list
run_input (QuantumCircuit or list): The QuantumCircuit (or list
of QuantumCircuit objects) to run
validate (bool): validate the Qobj before running (default: False).
parameter_binds (list): A list of parameter binding dictionaries.
Expand Down Expand Up @@ -182,10 +182,10 @@ def run(self, circuits, validate=False, parameter_binds=None, **run_options):
Raises:
ValueError: if run is not implemented
"""
if isinstance(circuits, (QuantumCircuit, Schedule, ScheduleBlock)):
circuits = [circuits]
if isinstance(run_input, (QuantumCircuit, Schedule, ScheduleBlock)):
run_input = [run_input]

if isinstance(circuits, (QasmQobj, PulseQobj)):
if isinstance(run_input, (QasmQobj, PulseQobj)):
warnings.warn(
"Using a qobj for run() is deprecated as of qiskit-aer 0.14"
" and will be removed no sooner than 3 months from that release"
Expand All @@ -202,19 +202,19 @@ def run(self, circuits, validate=False, parameter_binds=None, **run_options):
# run_options fields will take precidence over the value for those
# fields that are set via assemble.
if not run_options:
run_options = circuits.config.__dict__
run_options = run_input.config.__dict__
else:
run_options = copy.copy(run_options)
for key, value in circuits.config.__dict__.items():
for key, value in run_input.config.__dict__.items():
if key not in run_options and value is not None:
run_options[key] = value
if "parameter_binds" in run_options:
parameter_binds = run_options.pop("parameter_binds")
return self._run_qobj(circuits, validate, parameter_binds, **run_options)
return self._run_qobj(run_input, validate, parameter_binds, **run_options)

only_circuits = True
only_pulse = True
for circ in circuits:
for circ in run_input:
only_circuits &= isinstance(circ, QuantumCircuit)
only_pulse &= isinstance(circ, (ScheduleBlock, Schedule))

Expand All @@ -232,19 +232,19 @@ def run(self, circuits, validate=False, parameter_binds=None, **run_options):
# This path remains for DASK execution to split a qobj insttance
# into sub-qobj instances. This will be replaced with _run_circuits path
# in the near releases
return self._run_qobj(circuits, validate, parameter_binds, **run_options)
return self._run_qobj(run_input, validate, parameter_binds, **run_options)
else:
return self._run_circuits(circuits, parameter_binds, **run_options)
return self._run_circuits(run_input, parameter_binds, **run_options)
elif not only_circuits and only_pulse:
return self._run_qobj(circuits, validate, parameter_binds, **run_options)
return self._run_qobj(run_input, validate, parameter_binds, **run_options)
elif not only_circuits and not only_pulse:
raise TypeError(
"bad input to run() function;"
"circuits and schedules cannot be mixed in a single run"
)
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
2 changes: 1 addition & 1 deletion 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
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
Loading

0 comments on commit 2b2a1f3

Please sign in to comment.