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

Switch to using black for code formatting #6361

Merged
merged 6 commits into from
May 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
5 changes: 3 additions & 2 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ disable=spelling, # way too noisy
unnecessary-pass, # allow for methods with just "pass", for clarity
no-else-return, # relax "elif" after a clause with a return
docstring-first-line-empty, # relax docstring style
import-outside-toplevel
import-outside-toplevel,
bad-continuation, bad-whitespace # differences of opinion with black



Expand Down Expand Up @@ -212,7 +213,7 @@ max-nested-blocks=5
[FORMAT]

# Maximum number of characters on a single line.
max-line-length=100
max-line-length=105

# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
Expand Down
23 changes: 22 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ please ensure that:
1. The code follows the code style of the project and successfully
passes the tests. For convenience, you can execute `tox` locally,
which will run these checks and report any issues.

If your code fails the local style checks (specifically the black
code formatting check) you can use `tox -eblack` to automatically
fix update the code formatting.
2. The documentation has been updated accordingly. In particular, if a
function or class has been modified during the PR, please update the
*docstring* accordingly.
Expand Down Expand Up @@ -358,7 +362,24 @@ you just need to update the reference images as follows:
new tests should now pass.

Note: If you have run `test/ipynb/mpl_tester.ipynb` locally it is possible some file metadata has changed, **please do not commit and push changes to this file unless they were intentional**.
### Development Cycle

## Style and lint

Qiskit Terra uses 2 tools for verify code formatting and lint checking. The
Copy link
Member

Choose a reason for hiding this comment

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

I'd rather phase out the name Terra from docs that users see - just saying Qiskit (especially as black will likely be done in other repos too).

Copy link
Member Author

Choose a reason for hiding this comment

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

We can clean this up later, I was planning to update the overall contributing documentation when we've unified on using black everywhere: https://qiskit.org/documentation/contributing_to_qiskit.html#style-guide right now it just says pycodestyle and pylint

first tool is [black](https://github.com/psf/black) which is a code formatting
tool that will automatically update the code formatting to a consistent style.
The second tool is [pylint]https://www.pylint.org/) which is a code linter
which does a deeper analysis of the Python code to find both style issues and
potential bugs and other common issues in Python.

You can check that your local modifications conform to the style rules
by running `tox -elint` which will run `black` and `pylint` to check the local
code formatting and lint. If black returns a code formatting error you can
run `tox -eblack` to automatically update the code formatting to conform to
the style. However, if `pylint` returns any error you will have to fix these
issues by manually updating your code.

## Development Cycle

The development cycle for qiskit-terra is all handled in the open using
the project boards in Github for project management. We use milestones
Expand Down
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ lint:
python tools/find_optional_imports.py

style:
pycodestyle qiskit test
black --check qiskit test tools

black:
black qiskit test tools

# Use the -s (starting directory) flag for "unittest discover" is necessary,
# otherwise the QuantumCircuit header will be modified during the discovery.
Expand Down
2 changes: 1 addition & 1 deletion azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ stages:
- bash: |
set -e
source test-job/bin/activate
pycodestyle qiskit test
black --check qiskit test tools
pylint -rn qiskit test
tools/verify_headers.py qiskit test
python tools/find_optional_imports.py
Expand Down
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
[build-system]
requires = ["Cython>=0.27.1", "setuptools", "wheel"]

[tool.black]
line-length = 100
target-version = ['py36', 'py37', 'py38', 'py39']
26 changes: 18 additions & 8 deletions qiskit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@
warnings.warn(
"Using Qiskit with Python 3.6 is deprecated as of the 0.17.0 release. "
"Support for running Qiskit with Python 3.6 will be removed in a "
"future release.", DeprecationWarning)
"future release.",
DeprecationWarning,
)


class AerWrapper:
Expand All @@ -77,6 +79,7 @@ def __bool__(self):
if self.aer is None:
try:
from qiskit.providers import aer

self.aer = aer.Aer
except ImportError:
return False
Expand All @@ -86,11 +89,14 @@ def __getattr__(self, attr):
if not self.aer:
try:
from qiskit.providers import aer

self.aer = aer.Aer
except ImportError as exc:
raise ImportError('Could not import the Aer provider from the '
'qiskit-aer package. Install qiskit-aer or '
'check your installation.') from exc
raise ImportError(
"Could not import the Aer provider from the "
"qiskit-aer package. Install qiskit-aer or "
"check your installation."
) from exc
return getattr(self.aer, attr)


Expand All @@ -104,6 +110,7 @@ def __bool__(self):
if self.ibmq is None:
try:
from qiskit.providers import ibmq

self.ibmq = ibmq.IBMQ
except ImportError:
return False
Expand All @@ -113,12 +120,15 @@ def __getattr__(self, attr):
if not self.ibmq:
try:
from qiskit.providers import ibmq

self.ibmq = ibmq.IBMQ
except ImportError as exc:
raise ImportError('Could not import the IBMQ provider from the '
'qiskit-ibmq-provider package. Install '
'qiskit-ibmq-provider or check your '
'installation.') from exc
raise ImportError(
"Could not import the IBMQ provider from the "
"qiskit-ibmq-provider package. Install "
"qiskit-ibmq-provider or check your "
"installation."
) from exc
return getattr(self.ibmq, attr)


Expand Down
113 changes: 64 additions & 49 deletions qiskit/algorithms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,60 +165,75 @@
from .variational_algorithm import VariationalAlgorithm, VariationalResult
from .amplitude_amplifiers import Grover, GroverResult, AmplificationProblem
from .amplitude_estimators import (
AmplitudeEstimator, AmplitudeEstimatorResult,
AmplitudeEstimation, AmplitudeEstimationResult,
FasterAmplitudeEstimation, FasterAmplitudeEstimationResult,
IterativeAmplitudeEstimation, IterativeAmplitudeEstimationResult,
MaximumLikelihoodAmplitudeEstimation, MaximumLikelihoodAmplitudeEstimationResult,
EstimationProblem
AmplitudeEstimator,
AmplitudeEstimatorResult,
AmplitudeEstimation,
AmplitudeEstimationResult,
FasterAmplitudeEstimation,
FasterAmplitudeEstimationResult,
IterativeAmplitudeEstimation,
IterativeAmplitudeEstimationResult,
MaximumLikelihoodAmplitudeEstimation,
MaximumLikelihoodAmplitudeEstimationResult,
EstimationProblem,
)
from .eigen_solvers import NumPyEigensolver, Eigensolver, EigensolverResult
from .factorizers import Shor, ShorResult
from .linear_solvers import HHL, LinearSolver, NumPyLinearSolver, LinearSolverResult
from .minimum_eigen_solvers import (VQE, VQEResult, QAOA,
NumPyMinimumEigensolver,
MinimumEigensolver, MinimumEigensolverResult)
from .phase_estimators import (HamiltonianPhaseEstimation, HamiltonianPhaseEstimationResult,
PhaseEstimationScale, PhaseEstimation, PhaseEstimationResult)
from .minimum_eigen_solvers import (
VQE,
VQEResult,
QAOA,
NumPyMinimumEigensolver,
MinimumEigensolver,
MinimumEigensolverResult,
)
from .phase_estimators import (
HamiltonianPhaseEstimation,
HamiltonianPhaseEstimationResult,
PhaseEstimationScale,
PhaseEstimation,
PhaseEstimationResult,
)
from .exceptions import AlgorithmError

__all__ = [
'AlgorithmResult',
'VariationalAlgorithm',
'VariationalResult',
'AmplificationProblem',
'Grover',
'GroverResult',
'AmplitudeEstimator',
'AmplitudeEstimatorResult',
'AmplitudeEstimation',
'AmplitudeEstimationResult',
'FasterAmplitudeEstimation',
'FasterAmplitudeEstimationResult',
'IterativeAmplitudeEstimation',
'IterativeAmplitudeEstimationResult',
'MaximumLikelihoodAmplitudeEstimation',
'MaximumLikelihoodAmplitudeEstimationResult',
'EstimationProblem',
'NumPyEigensolver',
'LinearSolverResult',
'Eigensolver',
'EigensolverResult',
'Shor',
'ShorResult',
'VQE',
'VQEResult',
'QAOA',
'LinearSolver',
'HHL',
'NumPyLinearSolver',
'NumPyMinimumEigensolver',
'MinimumEigensolver',
'MinimumEigensolverResult',
'HamiltonianPhaseEstimation',
'HamiltonianPhaseEstimationResult',
'PhaseEstimationScale',
'PhaseEstimation',
'PhaseEstimationResult',
'AlgorithmError',
"AlgorithmResult",
"VariationalAlgorithm",
"VariationalResult",
"AmplificationProblem",
"Grover",
"GroverResult",
"AmplitudeEstimator",
"AmplitudeEstimatorResult",
"AmplitudeEstimation",
"AmplitudeEstimationResult",
"FasterAmplitudeEstimation",
"FasterAmplitudeEstimationResult",
"IterativeAmplitudeEstimation",
"IterativeAmplitudeEstimationResult",
"MaximumLikelihoodAmplitudeEstimation",
"MaximumLikelihoodAmplitudeEstimationResult",
"EstimationProblem",
"NumPyEigensolver",
"LinearSolverResult",
"Eigensolver",
"EigensolverResult",
"Shor",
"ShorResult",
"VQE",
"VQEResult",
"QAOA",
"LinearSolver",
"HHL",
"NumPyLinearSolver",
"NumPyMinimumEigensolver",
"MinimumEigensolver",
"MinimumEigensolverResult",
"HamiltonianPhaseEstimation",
"HamiltonianPhaseEstimationResult",
"PhaseEstimationScale",
"PhaseEstimation",
"PhaseEstimationResult",
"AlgorithmError",
]
24 changes: 15 additions & 9 deletions qiskit/algorithms/algorithm_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,23 @@


class AlgorithmResult(ABC):
""" Abstract Base Class for algorithm results."""
"""Abstract Base Class for algorithm results."""

def __str__(self) -> str:
result = {}
for name, value in inspect.getmembers(self):
if not name.startswith('_') and \
not inspect.ismethod(value) and not inspect.isfunction(value) and \
hasattr(self, name):
if (
not name.startswith("_")
and not inspect.ismethod(value)
and not inspect.isfunction(value)
and hasattr(self, name)
):

result[name] = value

return pprint.pformat(result, indent=4)

def combine(self, result: 'AlgorithmResult') -> None:
def combine(self, result: "AlgorithmResult") -> None:
"""
Any property from the argument that exists in the receiver is
updated.
Expand All @@ -43,15 +46,18 @@ def combine(self, result: 'AlgorithmResult') -> None:
TypeError: Argument is None
"""
if result is None:
raise TypeError('Argument result expected.')
raise TypeError("Argument result expected.")
if result == self:
return

# find any result public property that exists in the receiver
for name, value in inspect.getmembers(result):
if not name.startswith('_') and \
not inspect.ismethod(value) and not inspect.isfunction(value) and \
hasattr(self, name):
if (
not name.startswith("_")
and not inspect.ismethod(value)
and not inspect.isfunction(value)
and hasattr(self, name)
):
try:
setattr(self, name, value)
except AttributeError:
Expand Down
10 changes: 5 additions & 5 deletions qiskit/algorithms/amplitude_amplifiers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@
from .grover import Grover, GroverResult

__all__ = [
'AmplitudeAmplifier',
'AmplitudeAmplifierResult',
'AmplificationProblem',
'Grover',
'GroverResult'
"AmplitudeAmplifier",
"AmplitudeAmplifierResult",
"AmplificationProblem",
"Grover",
"GroverResult",
]
32 changes: 18 additions & 14 deletions qiskit/algorithms/amplitude_amplifiers/amplification_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,17 @@ class AmplificationProblem:
on the optimal bitstring.
"""

def __init__(self,
oracle: Union[QuantumCircuit, Statevector],
state_preparation: Optional[QuantumCircuit] = None,
grover_operator: Optional[QuantumCircuit] = None,
post_processing: Optional[Callable[[str], Any]] = None,
objective_qubits: Optional[Union[int, List[int]]] = None,
is_good_state: Optional[Union[
Callable[[str], bool], List[int], List[str], Statevector]] = None,
) -> None:
def __init__(
self,
oracle: Union[QuantumCircuit, Statevector],
state_preparation: Optional[QuantumCircuit] = None,
grover_operator: Optional[QuantumCircuit] = None,
post_processing: Optional[Callable[[str], Any]] = None,
objective_qubits: Optional[Union[int, List[int]]] = None,
is_good_state: Optional[
Union[Callable[[str], bool], List[int], List[str], Statevector]
] = None,
) -> None:
r"""
Args:
oracle: The oracle reflecting about the bad states.
Expand Down Expand Up @@ -159,15 +161,17 @@ def is_good_state(self) -> Callable[[str], bool]:
if all(isinstance(good_bitstr, str) for good_bitstr in self._is_good_state):
return lambda bitstr: bitstr in self._is_good_state
else:
return lambda bitstr: all(bitstr[good_index] == '1' # type:ignore
for good_index in self._is_good_state)
return lambda bitstr: all(
bitstr[good_index] == "1" # type:ignore
for good_index in self._is_good_state
)

return lambda bitstr: bitstr in self._is_good_state.probabilities_dict()

@is_good_state.setter
def is_good_state(self,
is_good_state: Union[Callable[[str], bool], List[int], List[str], Statevector]
) -> None:
def is_good_state(
self, is_good_state: Union[Callable[[str], bool], List[int], List[str], Statevector]
) -> None:
"""Set the ``is_good_state`` function.

Args:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class AmplitudeAmplifier(ABC):
"""The interface for amplification algorithms."""

@abstractmethod
def amplify(self, amplification_problem: AmplificationProblem) -> 'AmplificationResult':
def amplify(self, amplification_problem: AmplificationProblem) -> "AmplificationResult":
"""Run the amplification algorithm.

Args:
Expand Down
Loading