Skip to content

Commit

Permalink
Lint tweaks (Qiskit#6037)
Browse files Browse the repository at this point in the history
* more pylint useless supressions

* Union[float, int, complex] -> complex

* Drop float from Grover.iterations

* blackening

Co-authored-by: Luciano Bello <[email protected]>
  • Loading branch information
levbishop and 1ucian0 authored Jun 14, 2021
1 parent d5ab264 commit 5ec4278
Show file tree
Hide file tree
Showing 55 changed files with 61 additions and 94 deletions.
4 changes: 2 additions & 2 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ unsafe-load-any-extension=no
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code
extension-pkg-whitelist=
extension-pkg-whitelist=retworkx, numpy


[MESSAGES CONTROL]
Expand Down Expand Up @@ -297,7 +297,7 @@ ignore-mixin-members=yes
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=matplotlib.cm,numpy.random,retworkx
ignored-modules=

# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
Expand Down
3 changes: 1 addition & 2 deletions qiskit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

# pylint: disable=invalid-name,wrong-import-position

# pylint: disable=wrong-import-position

"""Main Qiskit public functionality."""

Expand Down
5 changes: 1 addition & 4 deletions qiskit/algorithms/amplitude_amplifiers/grover.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
"""Grover's search algorithm."""

import itertools
import logging
import operator
from typing import Iterator, List, Optional, Union

Expand All @@ -26,8 +25,6 @@
from .amplification_problem import AmplificationProblem
from .amplitude_amplifier import AmplitudeAmplifier, AmplitudeAmplifierResult

logger = logging.getLogger(__name__)


class Grover(AmplitudeAmplifier):
r"""Grover's Search algorithm.
Expand Down Expand Up @@ -105,7 +102,7 @@ class Grover(AmplitudeAmplifier):

def __init__(
self,
iterations: Optional[Union[int, List[int], Iterator[int], float]] = None,
iterations: Optional[Union[List[int], Iterator[int], int]] = None,
growth_rate: Optional[float] = None,
sample_from_iterations: bool = False,
quantum_instance: Optional[Union[QuantumInstance, Backend, BaseBackend]] = None,
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/minimum_eigen_solvers/vqe.py
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,7 @@ def get_optimal_vector(self) -> Union[List[float], Dict[str, int]]:
return min_vector

@property
def optimal_params(self) -> List[float]:
def optimal_params(self) -> np.ndarray:
"""The optimal parameters for the ansatz."""
if self._ret.optimal_point is None:
raise AlgorithmError("Cannot find optimal params before running the algorithm.")
Expand Down
6 changes: 3 additions & 3 deletions qiskit/algorithms/optimizers/aqgd.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,9 @@ def _compute_objective_fn_and_gradient(

def _update(
self,
params: np.array,
gradient: np.array,
mprev: np.array,
params: np.ndarray,
gradient: np.ndarray,
mprev: np.ndarray,
step_size: float,
momentum_coeff: float,
) -> Tuple[List[float], List[float]]:
Expand Down
2 changes: 0 additions & 2 deletions qiskit/circuit/equivalence_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@

"""Session gates."""

# pylint: disable=invalid-name

from .library.standard_gates.equivalence_library import StandardEquivalenceLibrary
from .equivalence import EquivalenceLibrary

Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/library/n_local/n_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -764,7 +764,7 @@ def assign_parameters(
self,
parameters: Union[dict, List[float], List[Parameter], ParameterVector],
inplace: bool = False,
param_dict: Optional[dict] = None, # pylint: disable=unused-argument
param_dict: Optional[dict] = None,
) -> Optional[QuantumCircuit]:
"""Assign parameters to the n-local circuit.
Expand Down
1 change: 0 additions & 1 deletion qiskit/circuit/library/n_local/qaoa_ansatz.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,6 @@ def initial_state(self, initial_state: Optional[QuantumCircuit]) -> None:

# we can't directly specify OperatorBase as a return type, it causes a circular import
# and pylint objects if return type is not documented
# pylint: disable=missing-return-type-doc
@property
def mixer_operator(self):
"""Returns an optional mixer operator expressed as an operator or a quantum circuit.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
"""Standard gates."""


# pylint: disable=invalid-name
import warnings
from qiskit.qasm import pi
from qiskit.circuit import EquivalenceLibrary, Parameter, QuantumCircuit, QuantumRegister
Expand Down
2 changes: 1 addition & 1 deletion qiskit/circuit/parameterexpression.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
HAS_SYMENGINE = False


ParameterValueType = Union["ParameterExpression", float, int]
ParameterValueType = Union["ParameterExpression", float]


class ParameterExpression:
Expand Down
8 changes: 4 additions & 4 deletions qiskit/circuit/quantumcircuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1455,7 +1455,7 @@ def qasm(self, formatted=False, filename=None, encoding=None):

elif (
type(instruction)
in [ # pylint: disable=unidiomatic-typecheck
in [
Gate,
Instruction,
]
Expand Down Expand Up @@ -2909,7 +2909,7 @@ def add_calibration(self, gate, qubits, schedule, params=None):
self._calibrations[gate][(tuple(qubits), tuple(params or []))] = schedule

# Functions only for scheduled circuits
def qubit_duration(self, *qubits: Union[Qubit, int]) -> Union[int, float]:
def qubit_duration(self, *qubits: Union[Qubit, int]) -> float:
"""Return the duration between the start and stop time of the first and last instructions,
excluding delays, over the supplied qubits. Its time unit is ``self.unit``.
Expand All @@ -2921,7 +2921,7 @@ def qubit_duration(self, *qubits: Union[Qubit, int]) -> Union[int, float]:
"""
return self.qubit_stop_time(*qubits) - self.qubit_start_time(*qubits)

def qubit_start_time(self, *qubits: Union[Qubit, int]) -> Union[int, float]:
def qubit_start_time(self, *qubits: Union[Qubit, int]) -> float:
"""Return the start time of the first instruction, excluding delays,
over the supplied qubits. Its time unit is ``self.unit``.
Expand Down Expand Up @@ -2963,7 +2963,7 @@ def qubit_start_time(self, *qubits: Union[Qubit, int]) -> Union[int, float]:

return 0 # If there are no instructions over bits

def qubit_stop_time(self, *qubits: Union[Qubit, int]) -> Union[int, float]:
def qubit_stop_time(self, *qubits: Union[Qubit, int]) -> float:
"""Return the stop time of the last instruction, excluding delays, over the supplied qubits.
Its time unit is ``self.unit``.
Expand Down
2 changes: 1 addition & 1 deletion qiskit/opflow/gradients/gradient_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from .derivative_base import DerivativeBase


class GradientBase(DerivativeBase): # pylint: disable=abstract-method
class GradientBase(DerivativeBase):
"""Base class for first-order operator gradient.
Convert an operator expression to the first-order gradient.
Expand Down
2 changes: 1 addition & 1 deletion qiskit/opflow/gradients/hessian_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from .derivative_base import DerivativeBase


class HessianBase(DerivativeBase): # pylint: disable=abstract-method
class HessianBase(DerivativeBase):
"""Base class for the Hessian of an expected value."""

def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion qiskit/opflow/gradients/natural_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def _reg_term_search(
regularization coefficient, solution to the regularization inverse problem
"""

def _get_curvature(x_lambda: List) -> Union[int, float]:
def _get_curvature(x_lambda: List) -> float:
"""Calculate Menger curvature
Menger, K. (1930). Untersuchungen ̈uber Allgemeine Metrik. Math. Ann.,103(1), 466–501
Expand Down
2 changes: 1 addition & 1 deletion qiskit/opflow/gradients/qfi_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from .circuit_qfis import CircuitQFI


class QFIBase(DerivativeBase): # pylint: disable=abstract-method
class QFIBase(DerivativeBase):

r"""Base class for Quantum Fisher Information (QFI).
Expand Down
2 changes: 0 additions & 2 deletions qiskit/opflow/operator_globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
from qiskit.opflow.primitive_ops.circuit_op import CircuitOp
from qiskit.opflow.state_fns.dict_state_fn import DictStateFn

# pylint: disable=invalid-name

# Digits of precision when returning values from eval functions. Without rounding, 1e-17 or 1e-32
# values often show up in place of 0, etc.
# Note: care needs to be taken in rounding otherwise some behavior may not be as expected. E.g
Expand Down
2 changes: 1 addition & 1 deletion qiskit/opflow/primitive_ops/pauli_sum_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ def to_spmatrix(self) -> spmatrix:
@classmethod
def from_list(
cls,
pauli_list: List[Tuple[str, Union[complex]]],
pauli_list: List[Tuple[str, complex]],
coeff: Union[complex, ParameterExpression] = 1.0,
) -> "PauliSumOp":
"""Construct from a pauli_list with the form [(pauli_str, coeffs)]
Expand Down
2 changes: 1 addition & 1 deletion qiskit/opflow/state_fns/cvar_measurement.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class CVaRMeasurement(OperatorStateFn):
# TODO allow normalization somehow?
def __init__(
self,
primitive: Union[OperatorBase] = None,
primitive: OperatorBase = None,
alpha: float = 1.0,
coeff: Union[complex, ParameterExpression] = 1.0,
) -> None:
Expand Down
2 changes: 1 addition & 1 deletion qiskit/opflow/state_fns/dict_state_fn.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ def eval(
from .operator_state_fn import OperatorStateFn

if isinstance(front, OperatorStateFn):
return cast(Union[OperatorBase, float, complex], front.adjoint().eval(self.adjoint()))
return cast(Union[OperatorBase, complex], front.adjoint().eval(self.adjoint()))

# All other OperatorBases go here
self_adjoint = cast(DictStateFn, self.adjoint())
Expand Down
2 changes: 1 addition & 1 deletion qiskit/providers/basicaer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,4 @@
from .exceptions import BasicAerError

# Global instance to be used as the entry point for convenience.
BasicAer = BasicAerProvider() # pylint: disable=invalid-name
BasicAer = BasicAerProvider()
1 change: 0 additions & 1 deletion qiskit/providers/models/pulsedefaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

# pylint: disable=missing-type-doc

"""Model and schema for pulse defaults."""
import copy
Expand Down
8 changes: 4 additions & 4 deletions qiskit/pulse/instruction_schedule_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,8 @@ def get(
self,
instruction: Union[str, Instruction],
qubits: Union[int, Iterable[int]],
*params: Union[int, float, complex, ParameterExpression],
**kwparams: Union[int, float, complex, ParameterExpression],
*params: Union[complex, ParameterExpression],
**kwparams: Union[complex, ParameterExpression],
) -> Union[Schedule, ScheduleBlock]:
"""Return the defined :py:class:`~qiskit.pulse.Schedule` or
:py:class:`~qiskit.pulse.ScheduleBlock` for the given instruction on the given qubits.
Expand Down Expand Up @@ -327,8 +327,8 @@ def pop(
self,
instruction: Union[str, Instruction],
qubits: Union[int, Iterable[int]],
*params: Union[int, float, complex, ParameterExpression],
**kwparams: Union[int, float, complex, ParameterExpression],
*params: Union[complex, ParameterExpression],
**kwparams: Union[complex, ParameterExpression],
) -> Union[Schedule, ScheduleBlock]:
"""Remove and return the defined schedule for the given instruction on the given
qubits.
Expand Down
2 changes: 1 addition & 1 deletion qiskit/pulse/library/discrete.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

# pylint: disable=missing-return-doc, invalid-name
# pylint: disable=missing-return-doc

"""Module for builtin discrete pulses.
Expand Down
4 changes: 2 additions & 2 deletions qiskit/pulse/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def params(self) -> List[str]:
"""
return sorted(self._params.copy())

def __call__(self, *args, **kwargs) -> Union[float, complex, ast.Expression]:
def __call__(self, *args, **kwargs) -> Union[complex, ast.Expression]:
"""Evaluate the expression with the given values of the expression's parameters.
Args:
Expand Down Expand Up @@ -141,7 +141,7 @@ def __call__(self, *args, **kwargs) -> Union[float, complex, ast.Expression]:
return expr.body.n

@staticmethod
def _match_ops(opr: ast.AST, opr_dict: Dict, *args) -> Union[float, complex]:
def _match_ops(opr: ast.AST, opr_dict: Dict, *args) -> complex:
"""Helper method to apply operators.
Args:
Expand Down
10 changes: 5 additions & 5 deletions qiskit/pulse/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -1433,7 +1433,7 @@ class ParameterizedSchedule:
def __init__(
self,
*schedules,
parameters: Optional[Dict[str, Union[float, complex]]] = None,
parameters: Optional[Dict[str, complex]] = None,
name: Optional[str] = None,
):

Expand Down Expand Up @@ -1469,8 +1469,8 @@ def parameters(self) -> Tuple[str]:

def bind_parameters(
self,
*args: Union[int, float, complex, ParameterExpression],
**kwargs: Union[int, float, complex, ParameterExpression],
*args: Union[complex, ParameterExpression],
**kwargs: Union[complex, ParameterExpression],
) -> Schedule:
"""Generate the Schedule from params to evaluate command expressions"""
bound_schedule = Schedule(name=self.name)
Expand Down Expand Up @@ -1517,8 +1517,8 @@ def bind_parameters(

def __call__(
self,
*args: Union[int, float, complex, ParameterExpression],
**kwargs: Union[int, float, complex, ParameterExpression],
*args: Union[complex, ParameterExpression],
**kwargs: Union[complex, ParameterExpression],
) -> Schedule:
return self.bind_parameters(*args, **kwargs)

Expand Down
2 changes: 1 addition & 1 deletion qiskit/pulse/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def format_meas_map(meas_map: List[List[int]]) -> Dict[int, List[int]]:
@functools.lru_cache(maxsize=None)
def format_parameter_value(
operand: Union[ParameterExpression],
) -> Union[ParameterExpression, int, float, complex]:
) -> Union[ParameterExpression, complex]:
"""Convert ParameterExpression into the most suitable data type.
Args:
Expand Down
2 changes: 1 addition & 1 deletion qiskit/qobj/pulse_qobj.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

# pylint: disable=invalid-name,redefined-builtin,method-hidden,arguments-differ
# pylint: disable=invalid-name,redefined-builtin,arguments-differ
# pylint: disable=super-init-not-called

"""Module providing definitions of Pulse Qobj classes."""
Expand Down
2 changes: 1 addition & 1 deletion qiskit/qobj/qasm_qobj.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

# pylint: disable=method-hidden,arguments-differ
# pylint: disable=arguments-differ

"""Module providing definitions of QASM Qobj classes."""

Expand Down
2 changes: 1 addition & 1 deletion qiskit/qobj/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,5 +65,5 @@ def validate_qobj_against_schema(qobj):
except JsonSchemaException as err:
raise SchemaValidationError(
f"Qobj validation failed. Specifically path: {err.path}" # pylint: disable=no-member
f" failed to fulfil {err.definition}" # pylint: disable=no-member
f" failed to fulfil {err.definition}"
) from err
1 change: 0 additions & 1 deletion qiskit/quantum_info/operators/base_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
from .mixins import GroupMixin


# pylint: disable = abstract-method
class BaseOperator(GroupMixin, ABC):
"""Abstract operator base class."""

Expand Down
2 changes: 1 addition & 1 deletion qiskit/quantum_info/operators/channel/transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

# pylint: disable=too-many-return-statements,unpacking-non-sequence
# pylint: disable=too-many-return-statements


"""
Expand Down
1 change: 0 additions & 1 deletion qiskit/quantum_info/operators/dihedral/dihedral.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
"""
CNOTDihedral operator class.
"""
# pylint: disable = abstract-method
import itertools
import numpy as np

Expand Down
1 change: 0 additions & 1 deletion qiskit/quantum_info/operators/linear_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,5 @@
from .mixins import LinearMixin, AdjointMixin, TolerancesMixin


# pylint: disable = abstract-method
class LinearOp(BaseOperator, AdjointMixin, LinearMixin, TolerancesMixin, ABC):
"""Abstract linear operator base class."""
Loading

0 comments on commit 5ec4278

Please sign in to comment.