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

Update pylint to 2.16 #1042

Merged
merged 15 commits into from
Mar 22, 2023
Merged
48 changes: 2 additions & 46 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ confidence=
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W"
disable=no-self-use, # disabled as it is too verbose
fixme, # disabled as TODOs would show up as warnings
disable=fixme, # disabled as TODOs would show up as warnings
protected-access, # disabled as we don't follow the public vs private
# convention strictly
duplicate-code, # disabled as it is too verbose
Expand All @@ -71,7 +70,6 @@ disable=no-self-use, # disabled as it is too verbose
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
assigning-non-slot # https://github.com/Qiskit/qiskit-terra/pull/7347#issuecomment-985007311


Expand All @@ -84,12 +82,6 @@ disable=no-self-use, # disabled as it is too verbose
# mypackage.mymodule.MyReporterClass.
output-format=text

# Put messages in a separate file for each module / package specified on the
# command line instead of printing them on stdout. Reports (if any) will be
# written in a file name "pylint_global.[txt|html]". This option is deprecated
# and it will be removed in Pylint 2.0.
files-output=no

# Tells whether to display a full report or only the messages
reports=yes

Expand Down Expand Up @@ -138,63 +130,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]+$
Copy link
Collaborator

Choose a reason for hiding this comment

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

Since pylint enforces PEP8 name conventions by default, do we need these custom regexes? Are there names we're using now that don't comply with PEP8?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I think this is a case of generating the default pylintrc with pylint and then modifying it, so these custom regexes just match the pylint default. We can try removing more stuff from the file. I just removed what I did because pylint was complaining that those options were no longer valid.

pylint has changed some defaults and removed some checkers since version 2.7 to be more in line with things like black.


# 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 @@ -222,12 +184,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 @@ -424,4 +380,4 @@ analyse-fallback-blocks=no

# Exceptions that will emit a warning when being caught. Defaults to
# "Exception"
overgeneral-exceptions=Exception
overgeneral-exceptions=builtins.Exception
10 changes: 5 additions & 5 deletions qiskit_experiments/calibration_management/basis_gate_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from warnings import warn

from qiskit.circuit import Parameter
import qiskit.pulse as pulse
from qiskit import pulse
from qiskit.pulse import ScheduleBlock

from qiskit_experiments.calibration_management.calibration_key_types import DefaultCalValue
Expand All @@ -33,7 +33,7 @@ class BasisGateLibrary(ABC, Mapping):
"""A base class for libraries of basis gates to make it easier to setup Calibrations."""

# Location where default parameter values are stored. These may be updated at construction.
__default_values__ = dict()
__default_values__ = {}

def __init__(
self,
Expand Down Expand Up @@ -150,7 +150,7 @@ def config(self) -> Dict[str, Any]:
return {
"class": self.__class__.__name__,
"kwargs": kwargs,
"hash": self.__hash__(),
"hash": hash(self),
}

@classmethod
Expand Down Expand Up @@ -258,7 +258,7 @@ def _build_schedules(self, basis_gates: Set[str]) -> Dict[str, ScheduleBlock]:
sched_sx = self._single_qubit_schedule("sx", dur, sx_amp, sigma, sx_beta)
sched_sy = self._single_qubit_schedule("sy", dur, sy_amp, sigma, sy_beta)

schedules = dict()
schedules = {}
for sched in [sched_x, sched_y, sched_sx, sched_sy]:
if sched.name in basis_gates:
schedules[sched.name] = sched
Expand Down Expand Up @@ -373,7 +373,7 @@ def default_values(self) -> List[DefaultCalValue]:
def _build_schedules(self, basis_gates: Set[str]) -> Dict[str, ScheduleBlock]:
"""Build the schedules of the CR library."""

schedules = dict()
schedules = {}

tgt_amp = Parameter("tgt_amp")
sigma = Parameter("σ")
Expand Down
2 changes: 1 addition & 1 deletion qiskit_experiments/curve_analysis/curve_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ def set_if_empty(self, **kwargs):
"""
for key, value in kwargs.items():
if self.get(key) is None:
self.__setitem__(key, value)
self[key] = value

@staticmethod
def format(value: Any) -> Any:
Expand Down
4 changes: 1 addition & 3 deletions qiskit_experiments/curve_analysis/curve_fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,7 @@ def fit_func(x, *params):
fit_func, xdata, ydata, sigma=sigma, p0=param_p0, bounds=param_bounds, **kwargs
)
except Exception as ex:
raise AnalysisError(
"scipy.optimize.curve_fit failed with error: {}".format(str(ex))
) from ex
raise AnalysisError(f"scipy.optimize.curve_fit failed with error: {str(ex)}") from ex

if np.isfinite(pcov).all():
# Keep parameter correlations in following analysis steps
Expand Down
2 changes: 1 addition & 1 deletion qiskit_experiments/curve_analysis/data_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def mean_xy_data(
if method == "iwv":
if sigma is None:
raise QiskitError(
"The inverse-weighted variance method cannot be used with" " `sigma=None`"
"The inverse-weighted variance method cannot be used with `sigma=None`"
)
for i in range(x_means.size):
# Get positions of y to average
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def __init__(self):
self._options = self._default_options()
self._set_options = set()
self._axis = None
self._curves = list()
self._curves = []

@property
def options(self) -> Options:
Expand Down
2 changes: 1 addition & 1 deletion qiskit_experiments/curve_analysis/visualization/curves.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def plot_curve_fit(
ax = get_non_gui_ax()

if fit_uncertainty is None:
fit_uncertainty = list()
fit_uncertainty = []
elif isinstance(fit_uncertainty, tuple):
fit_uncertainty = [fit_uncertainty]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,13 @@ def draw(
transform=axis.transAxes,
)

bbox_props = dict(boxstyle="square, pad=0.3", fc="white", ec="black", lw=1, alpha=0.8)
bbox_props = {
"boxstyle": "square, pad=0.3",
"fc": "white",
"ec": "black",
"lw": 1,
"alpha": 0.8,
}
report_handler.set_bbox(bbox_props)

axis.tick_params(labelsize=style.tick_label_size)
Expand Down Expand Up @@ -292,7 +298,13 @@ def draw(
transform=axis.transAxes,
)

bbox_props = dict(boxstyle="square, pad=0.3", fc="white", ec="black", lw=1, alpha=0.8)
bbox_props = {
"boxstyle": "square, pad=0.3",
"fc": "white",
"ec": "black",
"lw": 1,
"alpha": 0.8,
}
report_handler.set_bbox(bbox_props)

axis.tick_params(labelsize=style.tick_label_size)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def __init__(self, factor: float):
self.factor = factor

def __call__(self, x, pos=None):
return self.fix_minus("{:.3g}".format(x * self.factor))
return self.fix_minus(f"{x * self.factor:.3g}")

def initialize_canvas(self):
# Create axis if empty
Expand Down
20 changes: 10 additions & 10 deletions qiskit_experiments/data_processing/data_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,17 +67,17 @@ def _format_data(self, data: np.ndarray) -> np.ndarray:

def __json_encode__(self) -> Dict[str, Any]:
"""Return the config dict for this node."""
return dict(
cls=type(self),
args=tuple(getattr(self, "__init_args__", OrderedDict()).values()),
kwargs=dict(getattr(self, "__init_kwargs__", OrderedDict())),
)
return {
"cls": type(self),
"args": tuple(getattr(self, "__init_args__", OrderedDict()).values()),
"kwargs": dict(getattr(self, "__init_kwargs__", OrderedDict())),
}

@classmethod
def __json_decode__(cls, config: Dict[str, Any]) -> "DataAction":
"""Initialize a node from config dict."""
init_args = config.get("args", tuple())
init_kwargs = config.get("kwargs", dict())
init_args = config.get("args", ())
init_kwargs = config.get("kwargs", {})

return cls(*init_args, **init_kwargs)

Expand Down Expand Up @@ -181,9 +181,9 @@ def __json_encode__(self) -> Dict[str, Any]:
@classmethod
def __json_decode__(cls, config: Dict[str, Any]) -> "TrainableDataAction":
"""Initialize a node from config dict."""
init_args = config.get("args", tuple())
init_kwargs = config.get("kwargs", dict())
params = config.get("params", dict())
init_args = config.get("args", ())
init_kwargs = config.get("kwargs", {})
params = config.get("params", {})

instance = cls(*init_args, **init_kwargs)
instance.set_parameters(**params)
Expand Down
10 changes: 5 additions & 5 deletions qiskit_experiments/data_processing/data_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,11 +284,11 @@ def __repr__(self):

def __json_encode__(self) -> Dict[str, Any]:
"""Return the config dict for this data processor."""
return dict(
cls=type(self),
input_key=self._input_key,
nodes=self._nodes,
)
return {
"cls": type(self),
"input_key": self._input_key,
"nodes": self._nodes,
}

@classmethod
def __json_decode__(cls, config: Dict[str, Any]) -> "DataProcessor":
Expand Down
4 changes: 2 additions & 2 deletions qiskit_experiments/framework/configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def experiment(self):
f" qiskit-experiments version ({__version__}). You could try"
" installing a compatible qiskit-experiments version."
)
raise QiskitError("{}\nError Message:\n{}".format(msg, str(ex))) from ex
raise QiskitError(f"{msg}\nError Message:\n{str(ex)}") from ex


@dataclasses.dataclass(frozen=True)
Expand Down Expand Up @@ -121,4 +121,4 @@ def analysis(self):
f" qiskit-experiments version ({__version__}). You could try"
" installing a compatible qiskit-experiments version."
)
raise QiskitError("{}\nError Message:\n{}".format(msg, str(ex))) from ex
raise QiskitError(f"{msg}\nError Message:\n{str(ex)}") from ex
6 changes: 3 additions & 3 deletions qiskit_experiments/framework/experiment_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ def __init__(
self._experiment = experiment

# data stored in the database
metadata = dict()
metadata = {}
if experiment is not None:
metadata = copy.deepcopy(experiment._metadata())
source = metadata.pop(
Expand Down Expand Up @@ -802,7 +802,7 @@ def _add_job_data(
return jid, False
if status == JobStatus.ERROR:
LOG.error(
"Job data not added for errorred job [Job ID: %s]" "\nError message: %s",
"Job data not added for errorred job [Job ID: %s]\nError message: %s",
jid,
job.error_message(),
)
Expand Down Expand Up @@ -2053,7 +2053,7 @@ def __getattr__(self, name: str) -> Any:
return self._extra_data[name]
except KeyError:
# pylint: disable=raise-missing-from
raise AttributeError("Attribute %s is not defined" % name)
raise AttributeError(f"Attribute {name} is not defined")

def _safe_serialize_jobs(self):
"""Return serializable object for stored jobs"""
Expand Down
10 changes: 6 additions & 4 deletions qiskit_experiments/framework/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,14 +363,16 @@ def _deserialize_object_legacy(value: Dict) -> Any:
try:
class_name = value["__name__"]
mod_name = value["__module__"]
args = value.get("__args__", tuple())
kwargs = value.get("__kwargs__", dict())
args = value.get("__args__", ())
kwargs = value.get("__kwargs__", {})
mod = importlib.import_module(mod_name)
for name, cls in inspect.getmembers(mod, inspect.isclass):
if name == class_name:
return cls(*args, **kwargs)

raise Exception(f"Unable to find class {class_name} in module {mod_name}")
raise Exception( # pylint: disable=broad-exception-raised
f"Unable to find class {class_name} in module {mod_name}"
)

except Exception as ex: # pylint: disable=broad-except
traceback_msg = "".join(traceback.format_exception(type(ex), ex, ex.__traceback__))
Expand Down Expand Up @@ -441,7 +443,7 @@ def settings(self) -> Dict[str, Any]:
:class:`ExperimentDecoder` is invoked.
"""

def default(self, obj: Any) -> Any: # pylint: disable=arguments-differ
def default(self, obj: Any) -> Any: # pylint: disable=arguments-renamed
if istype(obj):
return _serialize_type(obj)
if hasattr(obj, "__json_encode__"):
Expand Down
2 changes: 1 addition & 1 deletion qiskit_experiments/framework/matplotlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ def get_non_gui_ax():
"""
figure = Figure()
_ = default_figure_canvas(figure)
return figure.subplots()
return figure.subplots(squeeze=False)[0, 0]
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,7 @@ def _run_analysis(
# Run composite analysis and extract T1 and T2 results
analysis_results, figures = super()._run_analysis(experiment_data)
t1_result = next(filter(lambda res: res.name == "T1", analysis_results))
t2_result = next(
filter(lambda res: res.name == "T2star" or res.name == "T2", analysis_results)
)
t2_result = next(filter(lambda res: res.name in {"T2star", "T2"}, analysis_results))

# Calculate Tphi from T1 and T2
tphi = 1 / (1 / t2_result.value - 1 / (2 * t1_result.value))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
from typing import Tuple

import numpy as np
import qiskit.pulse as pulse
from qiskit import QuantumCircuit
from qiskit.circuit import Gate, Parameter
from qiskit.exceptions import QiskitError
from qiskit import pulse

from qiskit_experiments.framework import BackendTiming
from qiskit_experiments.library.characterization.spectroscopy import Spectroscopy
Expand Down
Loading