Skip to content

[WIP] Add ruff configuration to pyproject.toml #9586

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

Closed
wants to merge 102 commits into from
Closed
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
102 commits
Select commit Hold shift + click to select a range
2da0e50
Add ruff configuration to pyproject.toml
jlapeyre Feb 14, 2023
535a583
Replace star import with explicit imports in fake_provider.py
jlapeyre Feb 14, 2023
adc0fba
Add missing imports not included in previous commit
jlapeyre Feb 14, 2023
57ef618
Use `left` rather than `l` for identifier
jlapeyre Feb 14, 2023
462b3ba
use "j not in" rather than "not j in"
jlapeyre Feb 14, 2023
812cda8
Change variable names so that ruff likes them
jlapeyre Feb 14, 2023
d577c4c
Use def rather than lambda
jlapeyre Feb 14, 2023
e652cb3
Comments for ruff config in pyproject.toml
jlapeyre Feb 15, 2023
e9735d3
Symbol imported twice
jlapeyre Feb 15, 2023
a6fd291
Rename variable for ruff
jlapeyre Feb 15, 2023
ae83178
Use "is not None"
jlapeyre Feb 15, 2023
30fed92
Use "x not in" rather than "not x in"
jlapeyre Feb 15, 2023
a30f15d
Squash or disablbe several ruff errors
jlapeyre Feb 15, 2023
7f3c267
Add ruff to CI tools, run black on python files
jlapeyre Feb 20, 2023
4a75693
Fix conflict
jlapeyre Feb 20, 2023
56c224f
Remove spurious trailing blank line
jlapeyre Feb 20, 2023
49350eb
Merge branch 'main' into use-ruff
jlapeyre Feb 20, 2023
a2f12ff
Add no-qa for ruff complaint
jlapeyre Feb 20, 2023
6c47b75
Merge branch 'main' into use-ruff
jlapeyre Feb 20, 2023
bed8619
test/ipynb/mpl/circuit/test_circuit_matplotlib_drawer.py:319:16: F401…
jlapeyre Feb 20, 2023
0ecbe91
test/python/algorithms/minimum_eigensolvers/test_qaoa.py:36:1: E741 A…
jlapeyre Feb 20, 2023
de596c1
test/python/algorithms/optimizers/utils/test_learning_rate.py:39:9: E…
jlapeyre Feb 20, 2023
785e917
test/python/algorithms/time_evolvers/test_trotter_qrte.py:72:16: E714…
jlapeyre Feb 21, 2023
7cadea3
test/python/circuit/test_circuit_load_from_qpy.py:1287:58: F401 [*] `…
jlapeyre Feb 21, 2023
cdc0abd
test/python/circuit/test_circuit_qasm.py:295:106: E501 Line too long …
jlapeyre Feb 21, 2023
52af6ee
test/python/circuit/test_circuit_qasm3.py:149:106: E501 Line too long…
jlapeyre Feb 21, 2023
9e75659
test/python/classical_function_compiler/bad_examples.py:33:16: F821 U…
jlapeyre Feb 21, 2023
b8861da
test/python/mock/test_mock_module_deprecation.py:26:51: F811 Redefini…
jlapeyre Feb 21, 2023
93a2bd0
test/python/opflow/test_gradients.py:722:9: E731 [*] Do not assign a …
jlapeyre Feb 21, 2023
cca56b9
test/python/opflow/test_op_construction.py:966:9: E741 Ambiguous vari…
jlapeyre Feb 21, 2023
38e405b
test/python/transpiler/test_passmanager_config.py:102:1: E101 Indenta…
jlapeyre Feb 21, 2023
90d3111
test/python/transpiler/test_sabre_layout.py:145:106: E501 Line too lo…
jlapeyre Feb 21, 2023
f9dc386
test/python/transpiler/test_solovay_kitaev.py:125:9: F841 [*] Local v…
jlapeyre Feb 21, 2023
4dc3362
test/python/utils/test_classtools.py:404:9: F841 [*] Local variable `…
jlapeyre Feb 21, 2023
342ab3d
test/python/visualization/test_circuit_latex.py:242:16: F401 [*] `qis…
jlapeyre Feb 21, 2023
1aad471
test/randomized/test_transpiler_equivalence.py:96:1: F403 `from qiski…
jlapeyre Feb 21, 2023
e235863
test/randomized/test_transpiler_equivalence.py:96:1: F403 `from qiski…
jlapeyre Feb 21, 2023
3d01dec
Make ruff check test directory in CI locally
jlapeyre Feb 21, 2023
ff23ac9
Move ruff overrides from pyproject.toml to inline in each file
jlapeyre Feb 21, 2023
1f45ccb
Add more targets to ruff checks
jlapeyre Feb 21, 2023
5b3878f
Remove unused imports in setup.py
jlapeyre Feb 21, 2023
344b4fb
Add setup.py as ruff target
jlapeyre Feb 21, 2023
e077b53
Merge branch 'main' into use-ruff
jlapeyre Feb 22, 2023
a4e20d4
Remove useless enumerate caught by ruff B007
jlapeyre Feb 22, 2023
824802f
Remove another useless enumerate caught by ruff B007
jlapeyre Feb 22, 2023
cdef401
Add check for unused loop variable in ruff config
jlapeyre Feb 22, 2023
3988d89
Add D419 Docstring is empty rule and fix offenses
jlapeyre Feb 22, 2023
ec19280
Add ruff rule and fix offenses D201 No blank lines allowed before fun…
jlapeyre Feb 22, 2023
77c37d0
Add some ruff docstring rules and fix offenses
jlapeyre Feb 22, 2023
fa6cc0d
Add some ruff docstring tests and fix offenses
jlapeyre Feb 22, 2023
24fe525
Add two ruff docstring rules and fix offenses
jlapeyre Feb 22, 2023
26acdc5
Add ruff rule "Replace unpacked list comprehension with a generator e…
jlapeyre Feb 22, 2023
ff4c127
Add ruff rule UP018
jlapeyre Feb 22, 2023
1a8fe2f
Add ruff rule UP034 Avoid extraneous parentheses
jlapeyre Feb 22, 2023
7417e06
Add ruff rule UP032 Use f-string instead of format call
jlapeyre Feb 22, 2023
2863fd4
Add ruff rule UP031 Use format specifiers instead of percent format
jlapeyre Feb 22, 2023
340071b
Run black to format changes in previous commit
jlapeyre Feb 22, 2023
10db888
Add ruff rule N818 Exception name `{errorname}` should be named with …
jlapeyre Feb 22, 2023
79a8577
Add ruff rule YTT misuse of sys.version or sys.version_info
jlapeyre Feb 22, 2023
4a5a077
Add ruff rule B904 raise exceptions with `raise ... from err`
jlapeyre Feb 22, 2023
1feaf3e
Add ruff rules B006 and B008
jlapeyre Feb 22, 2023
d4d029c
Add ruff rule C400 Unnecessary generator (rewrite as a `list` compreh…
jlapeyre Feb 22, 2023
9b6fd2c
Add ruff rule C401 Unnecessary generator (rewrite as a `set` comprehe…
jlapeyre Feb 22, 2023
8097467
Add ruff rule C402 Unnecessary generator (rewrite as a `dict` compreh…
jlapeyre Feb 22, 2023
934915f
Add all ruff rules in C4 (flake8-comprehensions) group
jlapeyre Feb 22, 2023
d2d5a12
Add ruff rule DTZ003 `datetime.datetime.utcnow()` not allowed
jlapeyre Feb 22, 2023
880faff
Reformat with black
jlapeyre Feb 22, 2023
08fd9ec
Add ruff rule ISC001 Implicitly concatenated string literals on one line
jlapeyre Feb 23, 2023
377ae17
Fix bug introduced in 10db888
jlapeyre Feb 23, 2023
492a248
Merge branch 'main' into use-ruff
jlapeyre Feb 24, 2023
e8db0e6
Fix typo in identifier in last commit circc -> circ
jlapeyre Feb 24, 2023
6ac5db8
Clean up pyproject.toml
jlapeyre Feb 24, 2023
e3fd158
Merge branch 'main' into use-ruff
jlapeyre Feb 24, 2023
8f0c9bf
Merge branch 'main' into use-ruff
jlapeyre Feb 24, 2023
5a74db6
Merge branch 'main' into use-ruff
jlapeyre Feb 27, 2023
2b91f8f
Merge branch 'main' into use-ruff
jlapeyre Feb 27, 2023
90aba9a
Revert "Add ruff rule N818 Exception name `{errorname}` should be nam…
jlapeyre Feb 27, 2023
0662c05
Revert "test/python/opflow/test_op_construction.py:966:9: E741 Ambigu…
jlapeyre Feb 27, 2023
148f28f
Rename l to lambda_ for identifer bound to Parameter(λ)
jlapeyre Feb 27, 2023
2c0f65d
Revert "test/python/algorithms/minimum_eigensolvers/test_qaoa.py:36:1…
jlapeyre Feb 27, 2023
9afc502
Ignore ruff rule E741, Do not use variables named 'I', 'O', or 'l'
jlapeyre Feb 27, 2023
7d1f185
Revert "Rename variable for ruff"
jlapeyre Feb 27, 2023
0783aff
Revert "Change variable names so that ruff likes them"
jlapeyre Feb 27, 2023
de395df
Revert "Use `left` rather than `l` for identifier"
jlapeyre Feb 27, 2023
d79662d
Use sys.float_info rather than np.finfo
jlapeyre Feb 28, 2023
3f35fdd
Use dictname.values() rather than .items() when key is not used
jlapeyre Feb 28, 2023
7a2889e
Remove unused testenv:ruff environment
jlapeyre Feb 28, 2023
d016769
Merge branch 'main' into use-ruff
jlapeyre Mar 2, 2023
55f408f
Remove temp file from revision control
jlapeyre Mar 2, 2023
20c854d
Merge branch 'main' into use-ruff
jlapeyre Mar 3, 2023
ffaf874
Use sys.float_info.epsilon instead of numpy
jlapeyre Mar 3, 2023
d590b72
Disable do not assign lambda expression, ruff E731
jlapeyre Mar 3, 2023
f02371b
Revert "test/python/opflow/test_gradients.py:722:9: E731 [*] Do not a…
jlapeyre Mar 3, 2023
adcd907
Revert "Use def rather than lambda"
jlapeyre Mar 3, 2023
97ebcb5
Revert "test/python/algorithms/optimizers/utils/test_learning_rate.py…
jlapeyre Mar 3, 2023
2d659c5
Simplify iteration over dict keys
jlapeyre Mar 3, 2023
80b078b
Disable ruff rule F821 undefined name
jlapeyre Mar 3, 2023
03f4b6b
Use slightly more readable version check
jlapeyre Mar 3, 2023
b60fc61
Merge branch 'main' into use-ruff
jlapeyre Mar 3, 2023
cb725b0
Merge branch 'main' into use-ruff
jlapeyre Mar 7, 2023
83b8ddf
Revert "Add ruff rule UP031 Use format specifiers instead of percent …
jlapeyre Mar 7, 2023
7b2ca00
Undo wrong improvement in sorting dict
jlapeyre Mar 7, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,26 @@ before-test = "pip install --only-binary=numpy,scipy numpy scipy"
[tool.cibuildwheel.linux]
before-all = "yum install -y wget && {package}/tools/install_rust.sh"
environment = 'PATH="$PATH:$HOME/.cargo/bin" CARGO_NET_GIT_FETCH_WITH_CLI="true"'


[tool.ruff]
line-length=105

[tool.ruff.per-file-ignores]
"__init__.py" = ["F401", "E402"] # imported but unused, Module level import not at top of file
"qiskit/circuit/library/__init__.py" = ["F403"] # import * used
"qiskit/extensions/__init__.py" = ["F403"]
"qiskit/providers/fake_provider/__init__.py" = ["F403"]
"qiskit/visualization/pulse/__init__.py" = ["F403"]
"qiskit/opflow/operator_globals.py" = ["E741"] # Ambiguous variable name `I`
"qiskit/quantum_info/operators/random.py" = ["F401"] # Should be fixed.
"qiskit/quantum_info/random.py" = ["F401"] # Should be fixed.
"qiskit/synthesis/discrete_basis/solovay_kitaev.py" = ["F821"] # Undefined name
"qiskit/test/decorators.py" = ["F401"] # `qiskit.providers.aer` imported but unused
"qiskit/tools/visualization.py" = ["F403"]
"qiskit/transpiler/passes/calibration/builders.py" = ["F401"]
"qiskit/transpiler/passes/optimization/hoare_opt.py" = ["F401"]
"qiskit/transpiler/passes/scheduling/calibration_creators.py" = ["F401"]
"qiskit/transpiler/passes/scheduling/rzx_templates.py" = ["F401"]


Copy link
Member

Choose a reason for hiding this comment

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

Per the ruff docs and some of your comments on docstrings in #1179 I'm wondering if we want to add

[tool.ruff.pydocstyle]
convention = "google"

here too

https://github.com/charliermarsh/ruff#does-ruff-support-numpy--or-google-style-docstrings

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's certainly worth trying.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I added some doc string checks. But in order to make this more manageable, I plan to instead defer them to a later PR (provided we actually make a switch to ruff) However, several doc string errors/suggestions made by ruff have been merged in recent PRs.

8 changes: 4 additions & 4 deletions qiskit/algorithms/amplitude_estimators/ae_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,20 @@ def bisect_max(f, a, b, steps=50, minwidth=1e-12, retval=False):
m = (a + b) / 2
fm = 0
while it < steps and b - a > minwidth:
l, r = (a + m) / 2, (m + b) / 2
fl, fm, fr = f(l), f(m), f(r)
left, r = (a + m) / 2, (m + b) / 2
fl, fm, fr = f(left), f(m), f(r)
Copy link
Member

Choose a reason for hiding this comment

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

I think we should disable whatever rule forbade this and revert this and all similar changes - it's not needed code churn, and makes this code block harder to read because there's now a split between using fl, fm, fr, m, r and left.

Personally I'm not sure I agree with enforcing variable-name conventions by automated checker anyway, because my experience is that there's more exceptions than they're worth, but I don't feel super strongly in general.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I agree. I think we've discussed this at least once in the past. For example, it can be much easier to reference an algorithm in a paper if you use the same symbols in the code. And the exceptions add clutter. I also don't feel strongly about whether to use a checker. Having said that, I often find that names are poorly chosen, and can make code difficult to read and search (Could use a better IDE in this case, I suppose)

Copy link
Contributor Author

@jlapeyre jlapeyre Feb 28, 2023

Choose a reason for hiding this comment

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

Fixed (reverted the commits) in #9586 (commits)
de395df Revert "Use left rather than l for identifier"
0783aff Revert "Change variable names so that ruff likes them"
7d1f185 Revert "Rename variable for ruff"
9afc502 Ignore ruff rule E741, Do not use variables named 'I', 'O', or 'l'
2c0f65d Revert "test/python/algorithms/minimum_eigensolvers/test_qaoa.py:36:1: E741 Ambiguous variable name: I"
148f28f Rename l to lambda_ for identifer bound to Parameter(λ)
0662c05 Revert "test/python/opflow/test_op_construction.py:966:9: E741 Ambiguous variable name: l"


# fl is the maximum
if fl > fm and fl > fr:
b = m
m = l
m = left
# fr is the maximum
elif fr > fm and fr > fl:
a = m
m = r
# fm is the maximum
else:
a = l
a = left
b = r

it += 1
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/gradients/spsa_sampler_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def _run(
gradient = []
indices = [circuits[i].parameters.data.index(p) for p in metadata[i]["parameters"]]
for j in range(circuits[i].num_parameters):
if not j in indices:
if j not in indices:
continue
# the gradient for jth parameter is the average of the gradients of the jth parameter
# for each batch.
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/optimizers/gsls.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def minimize(
var_lb = np.array([-np.inf] * x0.size)
var_ub = np.array([np.inf] * x0.size)
else:
var_lb = np.array([l for (l, _) in bounds])
var_lb = np.array([lower for (lower, _) in bounds])
var_ub = np.array([u for (_, u) in bounds])
Copy link
Member

Choose a reason for hiding this comment

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

Another case where the rename introduces a split between lower and u, though in this case it'd not be unclear to just change u to upper because the expression isn't long.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, whatever is chosen, upper and lower should be treated equally. Here and in a couple of other places.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

See commits mentioned in previous conversation.


x, fun, nfev, njev = self.ls_optimize(x0.size, fun, x0, var_lb, var_ub)
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/optimizers/nlopts/nloptimizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ def minimize(
bounds = [(None, None)] * x0.size

threshold = 3 * np.pi
low = [(l if l is not None else -threshold) for (l, u) in bounds]
high = [(u if u is not None else threshold) for (l, u) in bounds]
low = [(lower if lower is not None else -threshold) for (lower, u) in bounds]
high = [(u if u is not None else threshold) for (lower, u) in bounds]
Copy link
Member

Choose a reason for hiding this comment

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

Inconsistent naming conventions.

Copy link
Contributor Author

@jlapeyre jlapeyre Mar 3, 2023

Choose a reason for hiding this comment

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

Reverted in 0783aff


name = self._optimizer_names[self.get_nlopt_optimizer()]
opt = nlopt.opt(name, len(low))
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/optimizers/p_bfgs.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,8 @@ def minimize(
threshold = 2 * np.pi
if bounds is None:
bounds = [(-threshold, threshold)] * x0.size
low = [(l if l is not None else -threshold) for (l, u) in bounds]
high = [(u if u is not None else threshold) for (l, u) in bounds]
low = [(lower if lower is not None else -threshold) for (lower, u) in bounds]
high = [(u if u is not None else threshold) for (lower, u) in bounds]
Copy link
Member

Choose a reason for hiding this comment

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

Inconsistent naming.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Reverted in 0783aff


def optimize_runner(_queue, _i_pt): # Multi-process sampling
_sol, _opt, _nfev = self._optimize(fun, _i_pt, jac, bounds)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def lse_solver(self) -> Callable[[np.ndarray, np.ndarray], np.ndarray]:
def lse_solver(self, lse_solver: Callable[[np.ndarray, np.ndarray], np.ndarray] | None) -> None:
"""Sets an LSE solver. Uses a ``np.linalg.lstsq`` callable if ``None`` provided."""
if lse_solver is None:
lse_solver = lambda a, b: np.linalg.lstsq(a, b, rcond=1e-2)[0]
def lse_solver(a, b): return np.linalg.lstsq(a, b, rcond=1e-2)[0]

self._lse_solver = lse_solver

Expand Down
97 changes: 96 additions & 1 deletion qiskit/providers/fake_provider/fake_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,102 @@
from qiskit.providers.provider import ProviderV1
from qiskit.providers.exceptions import QiskitBackendNotFoundError

from .backends import *
from .backends import (
FakeAlmaden,
FakeArmonk,
FakeAthens,
FakeBelem,
FakeBoeblingen,
FakeBogota,
FakeBrooklyn,
FakeBurlington,
FakeCairo,
FakeCambridge,
FakeCambridgeAlternativeBasis,
FakeCasablanca,
FakeEssex,
FakeGuadalupe,
FakeHanoi,
FakeJakarta,
FakeJohannesburg,
FakeKolkata,
FakeLagos,
FakeLima,
FakeLondon,
FakeManila,
FakeManhattan,
FakeMelbourne,
FakeMontreal,
FakeMumbai,
FakeNairobi,
FakeOurense,
FakeParis,
FakePoughkeepsie,
FakeQuito,
FakeRochester,
FakeRome,
FakeRueschlikon,
FakeSantiago,
FakeSingapore,
FakeSydney,
FakeTenerife,
FakeTokyo,
FakeToronto,
FakeValencia,
FakeVigo,
FakeWashington,
FakeYorktown,
)

from .backends import (
FakeAlmadenV2,
FakeArmonkV2,
FakeAthensV2,
FakeAuckland,
FakeBelemV2,
FakeBoeblingenV2,
FakeBogotaV2,
FakeBrooklynV2,
FakeBurlingtonV2,
FakeCairoV2,
FakeCambridgeV2,
FakeCasablancaV2,
FakeEssexV2,
FakeGeneva,
FakeGuadalupeV2,
FakeHanoiV2,
FakeJakartaV2,
FakeJohannesburgV2,
FakeKolkataV2,
FakeLagosV2,
FakeLimaV2,
FakeLondonV2,
FakeManhattanV2,
FakeManilaV2,
FakeMelbourneV2,
FakeMontrealV2,
FakeMumbaiV2,
FakeNairobiV2,
FakeOslo,
FakeOurenseV2,
FakeParisV2,
FakePerth,
FakePrague,
FakePoughkeepsieV2,
FakeQuitoV2,
FakeRochesterV2,
FakeRomeV2,
FakeSantiagoV2,
FakeSherbrooke,
FakeSingaporeV2,
FakeSydneyV2,
FakeTorontoV2,
FakeValenciaV2,
FakeVigoV2,
FakeWashingtonV2,
FakeYorktownV2,
)

from .fake_qasm_simulator import FakeQasmSimulator
from .fake_openpulse_2q import FakeOpenPulse2Q
from .fake_openpulse_3q import FakeOpenPulse3Q
Expand Down
2 changes: 1 addition & 1 deletion qiskit/quantum_info/synthesis/xx_decompose/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def decomposition_hop(target_coordinate, strengths):
specialized_polytope = PolytopeData(
convex_subpolytopes=[
ConvexPolytopeData(
inequalities=[[v, h, l] for ((h, l), v) in coefficient_dict.items()]
inequalities=[[v, h, ineq2] for ((h, ineq2), v) in coefficient_dict.items()]
Copy link
Member

Choose a reason for hiding this comment

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

This is a particularly difficult to parse naming change for the l rule. (h, l) is easy to parse, but I'd have no idea what's going on with (h, ineq2) without the diff context.

Copy link
Contributor Author

@jlapeyre jlapeyre Mar 3, 2023

Choose a reason for hiding this comment

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

This has been reverted.

ineq2 is a pretty bad choice. I don't like ell, although the possibility of confusion is not quite as bad as it was in the olden days.

)
]
)
Expand Down
4 changes: 2 additions & 2 deletions qiskit/result/mitigation/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ def marganalize_counts(
) -> np.ndarray:
"""Marginalization of the Counts. Verify that number of clbits equals to the number of qubits."""
if clbits is not None:
qubits_len = len(qubits) if not qubits is None else 0
clbits_len = len(clbits) if not clbits is None else 0
qubits_len = len(qubits) if qubits is not None else 0
clbits_len = len(clbits) if clbits is not None else 0
if clbits_len not in (0, qubits_len):
raise QiskitError(
"Num qubits ({}) does not match number of clbits ({}).".format(
Expand Down
2 changes: 1 addition & 1 deletion qiskit/synthesis/clifford/clifford_decompose_layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,5 +387,5 @@ def _check_gates(qc, allowed_gates):
allowed_gates - list of strings
"""
for inst, _, _ in qc.data:
if not inst.name in allowed_gates:
if inst.name not in allowed_gates:
raise QiskitError("The gate name is not in the allowed_gates list.")
2 changes: 1 addition & 1 deletion qiskit/transpiler/passes/synthesis/unitary_synthesis.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def _error(circuit, target=None, qubits=None):
for key in keys:
target_op = target.operation_from_name(key)
# pylint: disable=unidiomatic-typecheck
if type(target_op) == type(inst.operation) and (
if type(target_op) == type(inst.operation) and ( # noqa: E721 Do not compare types
target_op.is_parameterized()
or all(
isclose(float(p1), float(p2))
Expand Down
4 changes: 2 additions & 2 deletions qiskit/transpiler/synthesis/graysynth.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

# Redirect getattrs to modules new location
# TODO: Deprecate in 0.24.0 and remove in 0.26.0
from qiskit.synthesis.linear.graysynth import *
from qiskit.synthesis.linear.graysynth import * # noqa: F403


def cnot_synth(state, section_size=2):
Expand Down Expand Up @@ -51,4 +51,4 @@ def cnot_synth(state, section_size=2):
Quantum Information & Computation 8.3 (2008): 282-294.
`arXiv:quant-ph/0302002 [quant-ph] <https://arxiv.org/abs/quant-ph/0302002>`_
"""
return synth_cnot_count_full_pmh(state, section_size=section_size)
return synth_cnot_count_full_pmh(state, section_size=section_size) # noqa: F405
3 changes: 2 additions & 1 deletion qiskit/transpiler/target.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@

# import QubitProperties here to provide convenience alias for building a
# full target
from qiskit.providers.backend import QubitProperties # pylint: disable=unused-import
# pylint: disable=unused-import
from qiskit.providers.backend import QubitProperties # noqa: F401
from qiskit.providers.models.backendproperties import BackendProperties

logger = logging.getLogger(__name__)
Expand Down
6 changes: 3 additions & 3 deletions qiskit/utils/backend_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ def has_ibmq():
"""Check if IBMQ is installed"""
if not _PROVIDER_CHECK.checked_ibmq:
try:
from qiskit.providers.ibmq import IBMQFactory
from qiskit.providers.ibmq.accountprovider import AccountProvider
from qiskit.providers.ibmq import IBMQFactory # noqa: F401
from qiskit.providers.ibmq.accountprovider import AccountProvider # noqa: F401

_PROVIDER_CHECK.has_ibmq = True
except Exception as ex: # pylint: disable=broad-except
Expand All @@ -70,7 +70,7 @@ def has_aer():
"""check if Aer is installed"""
if not _PROVIDER_CHECK.checked_aer:
try:
from qiskit.providers.aer import AerProvider
from qiskit.providers.aer import AerProvider # noqa: F401

_PROVIDER_CHECK.has_aer = True
except Exception as ex: # pylint: disable=broad-except
Expand Down
12 changes: 6 additions & 6 deletions qiskit/utils/mitigation/circuits.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ def count_keys(num_qubits: int) -> List[str]:

def complete_meas_cal(
qubit_list: List[int] = None,
qr: Union[int, List["QuantumRegister"]] = None,
cr: Union[int, List["ClassicalRegister"]] = None,
qr: Union[int, List["QuantumRegister"]] = None, # noqa: F821
cr: Union[int, List["ClassicalRegister"]] = None, # noqa: F821
circlabel: str = "",
) -> Tuple[List["QuantumCircuit"], List[str]]:
) -> Tuple[List["QuantumCircuit"], List[str]]: # noqa: F821
"""
Return a list of measurement calibration circuits for the full
Hilbert space.
Expand Down Expand Up @@ -114,10 +114,10 @@ def complete_meas_cal(

def tensored_meas_cal(
mit_pattern: List[List[int]] = None,
qr: Union[int, List["QuantumRegister"]] = None,
cr: Union[int, List["ClassicalRegister"]] = None,
qr: Union[int, List["QuantumRegister"]] = None, # noqa: F821
Copy link
Contributor

Choose a reason for hiding this comment

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

The docs say that F821 is an "undefined name error" -- do you think this is that because the type is in quotes?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes. That's it. I did not track down the reasoning. Of course, the name is in quotes precisely because the symbol is not defined. Maybe some people don't think this should be done, so there is a rule ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Cryoris Just because of this issue, I have reverted the application of this rule in 80b078b . There may be a way to sort this out, make a global exception or something. But for now, it's just in the way here.

cr: Union[int, List["ClassicalRegister"]] = None, # noqa: F821
circlabel: str = "",
) -> Tuple[List["QuantumCircuit"], List[List[int]]]:
) -> Tuple[List["QuantumCircuit"], List[List[int]]]: # noqa: F821
"""
Return a list of calibration circuits

Expand Down
2 changes: 1 addition & 1 deletion qiskit/visualization/circuit_visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@

# Temporary import from 0.22.0 to be deprecated in future
# pylint: disable=unused-import
from .circuit.circuit_visualization import circuit_drawer
from .circuit.circuit_visualization import circuit_drawer # noqa: F401
4 changes: 2 additions & 2 deletions qiskit/visualization/gate_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -910,7 +910,7 @@ def plot_error_map(backend, figsize=(12, 9), show_title=True, qubit_coordinates=
directed = False
if num_qubits < 20:
for edge in cmap:
if not [edge[1], edge[0]] in cmap:
if [edge[1], edge[0]] not in cmap:
directed = True
break

Expand Down Expand Up @@ -956,7 +956,7 @@ def plot_error_map(backend, figsize=(12, 9), show_title=True, qubit_coordinates=
directed = False
if num_qubits < 20:
for edge in cmap:
if not [edge[1], edge[0]] in cmap:
if [edge[1], edge[0]] not in cmap:
directed = True
break
for line in cmap.get_edges():
Expand Down
2 changes: 1 addition & 1 deletion qiskit/visualization/qcstyle.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@

# Temporary import from 0.22.0 to be deprecated in future
# pylint: disable=unused-wildcard-import,wildcard-import
from .circuit.qcstyle import *
from .circuit.qcstyle import * # noqa: F403