Skip to content

Commit 2eee566

Browse files
mtreinishlevbishop
andauthored
Switch to using black for code formatting (#6361)
* make compatible with pylint and pycodestyle * black config * flake8 compatible config * Missing newline * Add black check to CI and dev requirements This commit updates the CI configuration and local tox configuration to leverage black instead of pycodestyle. It adds a check job to ci and the tox lint job so we can quickly check if black has been run. A tox job named 'black' is added to run black on all the code in the repo. * Run black on everything This commit reformats all the code in the qiskit-terra repository to use black. It changes no functionality in the project and just adjusts the code formatting to be consistent and automated. If you are looking at this commit in the git log you can likely safely ignore any diff from this commit as it is just the result of running '`black' on the repo and instead you should look at any commits before or after this for functional changes. Co-authored-by: Lev S. Bishop <18673315+levbishop@users.noreply.github.com>
1 parent f2b1528 commit 2eee566

File tree

965 files changed

+46727
-37122
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

965 files changed

+46727
-37122
lines changed

.pylintrc

+3-2
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@ disable=spelling, # way too noisy
7171
unnecessary-pass, # allow for methods with just "pass", for clarity
7272
no-else-return, # relax "elif" after a clause with a return
7373
docstring-first-line-empty, # relax docstring style
74-
import-outside-toplevel
74+
import-outside-toplevel,
75+
bad-continuation, bad-whitespace # differences of opinion with black
7576

7677

7778

@@ -212,7 +213,7 @@ max-nested-blocks=5
212213
[FORMAT]
213214

214215
# Maximum number of characters on a single line.
215-
max-line-length=100
216+
max-line-length=105
216217

217218
# Regexp for a line that is allowed to be longer than the limit.
218219
ignore-long-lines=^\s*(# )?<?https?://\S+>?$

CONTRIBUTING.md

+22-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ please ensure that:
1818
1. The code follows the code style of the project and successfully
1919
passes the tests. For convenience, you can execute `tox` locally,
2020
which will run these checks and report any issues.
21+
22+
If your code fails the local style checks (specifically the black
23+
code formatting check) you can use `tox -eblack` to automatically
24+
fix update the code formatting.
2125
2. The documentation has been updated accordingly. In particular, if a
2226
function or class has been modified during the PR, please update the
2327
*docstring* accordingly.
@@ -358,7 +362,24 @@ you just need to update the reference images as follows:
358362
new tests should now pass.
359363

360364
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**.
361-
### Development Cycle
365+
366+
## Style and lint
367+
368+
Qiskit Terra uses 2 tools for verify code formatting and lint checking. The
369+
first tool is [black](https://github.com/psf/black) which is a code formatting
370+
tool that will automatically update the code formatting to a consistent style.
371+
The second tool is [pylint]https://www.pylint.org/) which is a code linter
372+
which does a deeper analysis of the Python code to find both style issues and
373+
potential bugs and other common issues in Python.
374+
375+
You can check that your local modifications conform to the style rules
376+
by running `tox -elint` which will run `black` and `pylint` to check the local
377+
code formatting and lint. If black returns a code formatting error you can
378+
run `tox -eblack` to automatically update the code formatting to conform to
379+
the style. However, if `pylint` returns any error you will have to fix these
380+
issues by manually updating your code.
381+
382+
## Development Cycle
362383

363384
The development cycle for qiskit-terra is all handled in the open using
364385
the project boards in Github for project management. We use milestones

Makefile

+4-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,10 @@ lint:
5151
python tools/find_optional_imports.py
5252

5353
style:
54-
pycodestyle qiskit test
54+
black --check qiskit test tools
55+
56+
black:
57+
black qiskit test tools
5558

5659
# Use the -s (starting directory) flag for "unittest discover" is necessary,
5760
# otherwise the QuantumCircuit header will be modified during the discovery.

azure-pipelines.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ stages:
274274
- bash: |
275275
set -e
276276
source test-job/bin/activate
277-
pycodestyle qiskit test
277+
black --check qiskit test tools
278278
pylint -rn qiskit test
279279
tools/verify_headers.py qiskit test
280280
python tools/find_optional_imports.py

pyproject.toml

+4
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,6 @@
11
[build-system]
22
requires = ["Cython>=0.27.1", "setuptools", "wheel"]
3+
4+
[tool.black]
5+
line-length = 100
6+
target-version = ['py36', 'py37', 'py38', 'py39']

qiskit/__init__.py

+18-8
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@
6464
warnings.warn(
6565
"Using Qiskit with Python 3.6 is deprecated as of the 0.17.0 release. "
6666
"Support for running Qiskit with Python 3.6 will be removed in a "
67-
"future release.", DeprecationWarning)
67+
"future release.",
68+
DeprecationWarning,
69+
)
6870

6971

7072
class AerWrapper:
@@ -77,6 +79,7 @@ def __bool__(self):
7779
if self.aer is None:
7880
try:
7981
from qiskit.providers import aer
82+
8083
self.aer = aer.Aer
8184
except ImportError:
8285
return False
@@ -86,11 +89,14 @@ def __getattr__(self, attr):
8689
if not self.aer:
8790
try:
8891
from qiskit.providers import aer
92+
8993
self.aer = aer.Aer
9094
except ImportError as exc:
91-
raise ImportError('Could not import the Aer provider from the '
92-
'qiskit-aer package. Install qiskit-aer or '
93-
'check your installation.') from exc
95+
raise ImportError(
96+
"Could not import the Aer provider from the "
97+
"qiskit-aer package. Install qiskit-aer or "
98+
"check your installation."
99+
) from exc
94100
return getattr(self.aer, attr)
95101

96102

@@ -104,6 +110,7 @@ def __bool__(self):
104110
if self.ibmq is None:
105111
try:
106112
from qiskit.providers import ibmq
113+
107114
self.ibmq = ibmq.IBMQ
108115
except ImportError:
109116
return False
@@ -113,12 +120,15 @@ def __getattr__(self, attr):
113120
if not self.ibmq:
114121
try:
115122
from qiskit.providers import ibmq
123+
116124
self.ibmq = ibmq.IBMQ
117125
except ImportError as exc:
118-
raise ImportError('Could not import the IBMQ provider from the '
119-
'qiskit-ibmq-provider package. Install '
120-
'qiskit-ibmq-provider or check your '
121-
'installation.') from exc
126+
raise ImportError(
127+
"Could not import the IBMQ provider from the "
128+
"qiskit-ibmq-provider package. Install "
129+
"qiskit-ibmq-provider or check your "
130+
"installation."
131+
) from exc
122132
return getattr(self.ibmq, attr)
123133

124134

qiskit/algorithms/__init__.py

+64-49
Original file line numberDiff line numberDiff line change
@@ -165,60 +165,75 @@
165165
from .variational_algorithm import VariationalAlgorithm, VariationalResult
166166
from .amplitude_amplifiers import Grover, GroverResult, AmplificationProblem
167167
from .amplitude_estimators import (
168-
AmplitudeEstimator, AmplitudeEstimatorResult,
169-
AmplitudeEstimation, AmplitudeEstimationResult,
170-
FasterAmplitudeEstimation, FasterAmplitudeEstimationResult,
171-
IterativeAmplitudeEstimation, IterativeAmplitudeEstimationResult,
172-
MaximumLikelihoodAmplitudeEstimation, MaximumLikelihoodAmplitudeEstimationResult,
173-
EstimationProblem
168+
AmplitudeEstimator,
169+
AmplitudeEstimatorResult,
170+
AmplitudeEstimation,
171+
AmplitudeEstimationResult,
172+
FasterAmplitudeEstimation,
173+
FasterAmplitudeEstimationResult,
174+
IterativeAmplitudeEstimation,
175+
IterativeAmplitudeEstimationResult,
176+
MaximumLikelihoodAmplitudeEstimation,
177+
MaximumLikelihoodAmplitudeEstimationResult,
178+
EstimationProblem,
174179
)
175180
from .eigen_solvers import NumPyEigensolver, Eigensolver, EigensolverResult
176181
from .factorizers import Shor, ShorResult
177182
from .linear_solvers import HHL, LinearSolver, NumPyLinearSolver, LinearSolverResult
178-
from .minimum_eigen_solvers import (VQE, VQEResult, QAOA,
179-
NumPyMinimumEigensolver,
180-
MinimumEigensolver, MinimumEigensolverResult)
181-
from .phase_estimators import (HamiltonianPhaseEstimation, HamiltonianPhaseEstimationResult,
182-
PhaseEstimationScale, PhaseEstimation, PhaseEstimationResult)
183+
from .minimum_eigen_solvers import (
184+
VQE,
185+
VQEResult,
186+
QAOA,
187+
NumPyMinimumEigensolver,
188+
MinimumEigensolver,
189+
MinimumEigensolverResult,
190+
)
191+
from .phase_estimators import (
192+
HamiltonianPhaseEstimation,
193+
HamiltonianPhaseEstimationResult,
194+
PhaseEstimationScale,
195+
PhaseEstimation,
196+
PhaseEstimationResult,
197+
)
183198
from .exceptions import AlgorithmError
184199

185200
__all__ = [
186-
'AlgorithmResult',
187-
'VariationalAlgorithm',
188-
'VariationalResult',
189-
'AmplificationProblem',
190-
'Grover',
191-
'GroverResult',
192-
'AmplitudeEstimator',
193-
'AmplitudeEstimatorResult',
194-
'AmplitudeEstimation',
195-
'AmplitudeEstimationResult',
196-
'FasterAmplitudeEstimation',
197-
'FasterAmplitudeEstimationResult',
198-
'IterativeAmplitudeEstimation',
199-
'IterativeAmplitudeEstimationResult',
200-
'MaximumLikelihoodAmplitudeEstimation',
201-
'MaximumLikelihoodAmplitudeEstimationResult',
202-
'EstimationProblem',
203-
'NumPyEigensolver',
204-
'LinearSolverResult',
205-
'Eigensolver',
206-
'EigensolverResult',
207-
'Shor',
208-
'ShorResult',
209-
'VQE',
210-
'VQEResult',
211-
'QAOA',
212-
'LinearSolver',
213-
'HHL',
214-
'NumPyLinearSolver',
215-
'NumPyMinimumEigensolver',
216-
'MinimumEigensolver',
217-
'MinimumEigensolverResult',
218-
'HamiltonianPhaseEstimation',
219-
'HamiltonianPhaseEstimationResult',
220-
'PhaseEstimationScale',
221-
'PhaseEstimation',
222-
'PhaseEstimationResult',
223-
'AlgorithmError',
201+
"AlgorithmResult",
202+
"VariationalAlgorithm",
203+
"VariationalResult",
204+
"AmplificationProblem",
205+
"Grover",
206+
"GroverResult",
207+
"AmplitudeEstimator",
208+
"AmplitudeEstimatorResult",
209+
"AmplitudeEstimation",
210+
"AmplitudeEstimationResult",
211+
"FasterAmplitudeEstimation",
212+
"FasterAmplitudeEstimationResult",
213+
"IterativeAmplitudeEstimation",
214+
"IterativeAmplitudeEstimationResult",
215+
"MaximumLikelihoodAmplitudeEstimation",
216+
"MaximumLikelihoodAmplitudeEstimationResult",
217+
"EstimationProblem",
218+
"NumPyEigensolver",
219+
"LinearSolverResult",
220+
"Eigensolver",
221+
"EigensolverResult",
222+
"Shor",
223+
"ShorResult",
224+
"VQE",
225+
"VQEResult",
226+
"QAOA",
227+
"LinearSolver",
228+
"HHL",
229+
"NumPyLinearSolver",
230+
"NumPyMinimumEigensolver",
231+
"MinimumEigensolver",
232+
"MinimumEigensolverResult",
233+
"HamiltonianPhaseEstimation",
234+
"HamiltonianPhaseEstimationResult",
235+
"PhaseEstimationScale",
236+
"PhaseEstimation",
237+
"PhaseEstimationResult",
238+
"AlgorithmError",
224239
]

qiskit/algorithms/algorithm_result.py

+15-9
Original file line numberDiff line numberDiff line change
@@ -20,20 +20,23 @@
2020

2121

2222
class AlgorithmResult(ABC):
23-
""" Abstract Base Class for algorithm results."""
23+
"""Abstract Base Class for algorithm results."""
2424

2525
def __str__(self) -> str:
2626
result = {}
2727
for name, value in inspect.getmembers(self):
28-
if not name.startswith('_') and \
29-
not inspect.ismethod(value) and not inspect.isfunction(value) and \
30-
hasattr(self, name):
28+
if (
29+
not name.startswith("_")
30+
and not inspect.ismethod(value)
31+
and not inspect.isfunction(value)
32+
and hasattr(self, name)
33+
):
3134

3235
result[name] = value
3336

3437
return pprint.pformat(result, indent=4)
3538

36-
def combine(self, result: 'AlgorithmResult') -> None:
39+
def combine(self, result: "AlgorithmResult") -> None:
3740
"""
3841
Any property from the argument that exists in the receiver is
3942
updated.
@@ -43,15 +46,18 @@ def combine(self, result: 'AlgorithmResult') -> None:
4346
TypeError: Argument is None
4447
"""
4548
if result is None:
46-
raise TypeError('Argument result expected.')
49+
raise TypeError("Argument result expected.")
4750
if result == self:
4851
return
4952

5053
# find any result public property that exists in the receiver
5154
for name, value in inspect.getmembers(result):
52-
if not name.startswith('_') and \
53-
not inspect.ismethod(value) and not inspect.isfunction(value) and \
54-
hasattr(self, name):
55+
if (
56+
not name.startswith("_")
57+
and not inspect.ismethod(value)
58+
and not inspect.isfunction(value)
59+
and hasattr(self, name)
60+
):
5561
try:
5662
setattr(self, name, value)
5763
except AttributeError:

qiskit/algorithms/amplitude_amplifiers/__init__.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@
1717
from .grover import Grover, GroverResult
1818

1919
__all__ = [
20-
'AmplitudeAmplifier',
21-
'AmplitudeAmplifierResult',
22-
'AmplificationProblem',
23-
'Grover',
24-
'GroverResult'
20+
"AmplitudeAmplifier",
21+
"AmplitudeAmplifierResult",
22+
"AmplificationProblem",
23+
"Grover",
24+
"GroverResult",
2525
]

qiskit/algorithms/amplitude_amplifiers/amplification_problem.py

+18-14
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,17 @@ class AmplificationProblem:
2727
on the optimal bitstring.
2828
"""
2929

30-
def __init__(self,
31-
oracle: Union[QuantumCircuit, Statevector],
32-
state_preparation: Optional[QuantumCircuit] = None,
33-
grover_operator: Optional[QuantumCircuit] = None,
34-
post_processing: Optional[Callable[[str], Any]] = None,
35-
objective_qubits: Optional[Union[int, List[int]]] = None,
36-
is_good_state: Optional[Union[
37-
Callable[[str], bool], List[int], List[str], Statevector]] = None,
38-
) -> None:
30+
def __init__(
31+
self,
32+
oracle: Union[QuantumCircuit, Statevector],
33+
state_preparation: Optional[QuantumCircuit] = None,
34+
grover_operator: Optional[QuantumCircuit] = None,
35+
post_processing: Optional[Callable[[str], Any]] = None,
36+
objective_qubits: Optional[Union[int, List[int]]] = None,
37+
is_good_state: Optional[
38+
Union[Callable[[str], bool], List[int], List[str], Statevector]
39+
] = None,
40+
) -> None:
3941
r"""
4042
Args:
4143
oracle: The oracle reflecting about the bad states.
@@ -159,15 +161,17 @@ def is_good_state(self) -> Callable[[str], bool]:
159161
if all(isinstance(good_bitstr, str) for good_bitstr in self._is_good_state):
160162
return lambda bitstr: bitstr in self._is_good_state
161163
else:
162-
return lambda bitstr: all(bitstr[good_index] == '1' # type:ignore
163-
for good_index in self._is_good_state)
164+
return lambda bitstr: all(
165+
bitstr[good_index] == "1" # type:ignore
166+
for good_index in self._is_good_state
167+
)
164168

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

167171
@is_good_state.setter
168-
def is_good_state(self,
169-
is_good_state: Union[Callable[[str], bool], List[int], List[str], Statevector]
170-
) -> None:
172+
def is_good_state(
173+
self, is_good_state: Union[Callable[[str], bool], List[int], List[str], Statevector]
174+
) -> None:
171175
"""Set the ``is_good_state`` function.
172176
173177
Args:

qiskit/algorithms/amplitude_amplifiers/amplitude_amplifier.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class AmplitudeAmplifier(ABC):
2525
"""The interface for amplification algorithms."""
2626

2727
@abstractmethod
28-
def amplify(self, amplification_problem: AmplificationProblem) -> 'AmplificationResult':
28+
def amplify(self, amplification_problem: AmplificationProblem) -> "AmplificationResult":
2929
"""Run the amplification algorithm.
3030
3131
Args:

0 commit comments

Comments
 (0)