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 to pylint 2.13 #5156

Merged
merged 6 commits into from
Mar 29, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions cirq-core/cirq/circuits/circuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -1359,7 +1359,7 @@ def zip(
same moment index.

Args:
circuits: The circuits to merge together.
*circuits: The circuits to merge together.
align: The alignment for the zip, see `cirq.Alignment`.

Returns:
Expand Down Expand Up @@ -1441,7 +1441,7 @@ def tetris_concat(
False

Args:
circuits: The circuits to concatenate.
*circuits: The circuits to concatenate.
align: When to stop when sliding the circuits together.
'left': Stop when the starts of the circuits align.
'right': Stop when the ends of the circuits align.
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/circuits/circuit_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ def with_qubits(self, *new_qubits: 'cirq.Qid') -> 'cirq.CircuitOperation':
"""Returns a copy of this operation with an updated qubit mapping.

Args:
new_qubits: A list of qubits to target. Qubits in this list are
*new_qubits: A list of qubits to target. Qubits in this list are
matched to qubits in the circuit following default qubit order,
ignoring any existing qubit map.

Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/circuits/moment.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ def with_operations(self, *contents: 'cirq.OP_TREE') -> 'cirq.Moment':
"""Returns a new moment with the given contents added.

Args:
contents: New operations to add to this moment.
*contents: New operations to add to this moment.

Returns:
The new moment.
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/devices/named_topologies.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def draw_gridlike(
ax: Optional matplotlib axis to use for drawing.
tilted: If True, directly position as (row, column); otherwise,
rotate 45 degrees to accommodate google-style diagonal grids.
kwargs: Additional arguments to pass to `nx.draw_networkx`.
**kwargs: Additional arguments to pass to `nx.draw_networkx`.

Returns:
A positions dictionary mapping nodes to (x, y) coordinates suitable for future calls
Expand Down Expand Up @@ -126,7 +126,7 @@ def draw(self, ax=None, tilted: bool = True, **kwargs) -> Dict[Any, Tuple[int, i
Args:
ax: Optional matplotlib axis to use for drawing.
tilted: If True, draw as a horizontal line. Otherwise, draw on a diagonal.
kwargs: Additional arguments to pass to `nx.draw_networkx`.
**kwargs: Additional arguments to pass to `nx.draw_networkx`.
"""
g2 = nx.relabel_nodes(self.graph, {n: (n, 1) for n in self.graph.nodes})
return draw_gridlike(g2, ax=ax, tilted=tilted, **kwargs)
Expand Down Expand Up @@ -217,7 +217,7 @@ def draw(self, ax=None, tilted=True, **kwargs):
ax: Optional matplotlib axis to use for drawing.
tilted: If True, directly position as (row, column); otherwise,
rotate 45 degrees to accommodate the diagonal nature of this topology.
kwargs: Additional arguments to pass to `nx.draw_networkx`.
**kwargs: Additional arguments to pass to `nx.draw_networkx`.
"""
return draw_gridlike(self.graph, ax=ax, tilted=tilted, **kwargs)

Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/experiments/qubit_characterizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def plot(self, axes: Optional[List[plt.Axes]] = None, **plot_kwargs: Any) -> Lis
axes: A list of 2 `plt.Axes` instances. Note that they must be in
3d projections. If not given, a new figure is created with 2
axes and the plotted figure is shown.
plot_kwargs: The optional kwargs passed to bar3d.
**plot_kwargs: The optional kwargs passed to bar3d.

Returns:
the list of `plt.Axes` being plotted on.
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/linalg/decompositions.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ def scatter_plot_normalized_kak_interaction_coefficients(
wireframe. Defaults to `True`.
ax: A matplotlib 3d axes object to plot into. If not specified, a new
figure is created, plotted, and shown.
kwargs: Arguments forwarded into the call to `scatter` that plots the
**kwargs: Arguments forwarded into the call to `scatter` that plots the
points. Working arguments include color `c='blue'`, scale `s=2`,
labelling `label="theta=pi/4"`, etc. For reference see the
`matplotlib.pyplot.scatter` documentation:
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/arithmetic_operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def with_registers(self: TSelf, *new_registers: Union[int, Sequence['cirq.Qid']]
"""Returns the same operation targeting different registers.

Args:
new_registers: The new values that should be returned by the
*new_registers: The new values that should be returned by the
`registers` method.

Returns:
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/fourier_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def qft(
equivalently `cirq.inverse(cirq.qft(*qubits))`.

Args:
qubits: The qubits to apply the qft to.
*qubits: The qubits to apply the qft to.
without_reverse: When set, swap gates at the end of the qft are omitted.
This reverses the qubit order relative to the standard qft effect,
but makes the gate cheaper to apply.
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/pauli_string_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1311,7 +1311,7 @@ def test_pauli_string_expectation_from_density_matrix_pure_state_with_coef():
z0z2 = cirq.Z(qs[0]) * cirq.Z(qs[2]) * -1
z1x2 = -cirq.Z(qs[1]) * cirq.X(qs[2])

for state in [rho, rho.reshape(2, 2, 2, 2, 2, 2, 2, 2)]:
for state in [rho, rho.reshape((2, 2, 2, 2, 2, 2, 2, 2))]:
np.testing.assert_allclose(z0z1.expectation_from_density_matrix(state, q_map), -0.123)
np.testing.assert_allclose(z0z2.expectation_from_density_matrix(state, q_map), 0)
np.testing.assert_allclose(z1x2.expectation_from_density_matrix(state, q_map), 1)
Expand Down
8 changes: 4 additions & 4 deletions cirq-core/cirq/ops/raw_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,7 @@ def with_qubits(self: TSelf, *new_qubits: 'cirq.Qid') -> TSelf:
"""Returns the same operation, but applied to different qubits.

Args:
new_qubits: The new qubits to apply the operation to. The order must
*new_qubits: The new qubits to apply the operation to. The order must
exactly match the order of qubits returned from the operation's
`qubits` property.
"""
Expand Down Expand Up @@ -489,7 +489,7 @@ def with_tags(self, *new_tags: Hashable) -> 'cirq.Operation':
also restrict the operation to be JSON serializable.

Args:
new_tags: The tags to wrap this operation in.
*new_tags: The tags to wrap this operation in.
"""
if not new_tags:
return self
Expand Down Expand Up @@ -529,7 +529,7 @@ def controlled_by(
are specified, returns self.

Args:
control_qubits: Qubits to control the operation by. Required.
*control_qubits: Qubits to control the operation by. Required.
control_values: For which control qubit values to apply the
operation. A sequence of the same length as `control_qubits`
where each entry is an integer (or set of integers)
Expand Down Expand Up @@ -627,7 +627,7 @@ def with_classical_controls(
since tags are considered a local attribute.

Args:
conditions: A list of measurement keys, strings that can be parsed
*conditions: A list of measurement keys, strings that can be parsed
into measurement keys, or sympy expressions where the free
symbols are measurement key strings.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def assert_optimizes(before: cirq.Circuit, expected: cirq.Circuit, **kwargs):
Args:
before: The input circuit to optimize.
expected: The expected result of optimization to compare against.
kwargs: Any extra arguments to pass to the
**kwargs: Any extra arguments to pass to the
``MergeInteractionsToSqrtIswap`` constructor.
"""
actual = before.copy()
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/protocols/decompose_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,10 +279,10 @@ def decompose_once(val: Any, default=RaiseTypeErrorIfNotProvided, *args, **kwarg
`_decompose_` method or that method returns `NotImplemented` or
`None`. If not specified, non-decomposable values cause a
`TypeError`.
args: Positional arguments to forward into the `_decompose_` method of
*args: Positional arguments to forward into the `_decompose_` method of
`val`. For example, this is used to tell gates what qubits they are
being applied to.
kwargs: Keyword arguments to forward into the `_decompose_` method of
**kwargs: Keyword arguments to forward into the `_decompose_` method of
`val`.

Returns:
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/qis/states.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ def infer_qid_shape(*states: 'cirq.QUANTUM_STATE_LIKE') -> Tuple[int, ...]:
an error is raised.

Args:
states: The states for which to infer the qid shape.
*states: The states for which to infer the qid shape.

Returns:
The inferred qid shape.
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/testing/deprecation.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def assert_deprecated(*msgs: str, deadline: str, count: Optional[int] = 1) -> It
>>> # do something deprecated

Args:
msgs: messages that should match the warnings captured
*msgs: messages that should match the warnings captured
deadline: the expected deadline the feature will be deprecated by. Has to follow the format
vX.Y (minor versions only)
count: if None count of messages is not asserted, otherwise the number of deprecation
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/testing/equals_tester.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def make_equality_group(self, *factories: Callable[[], Any]):
Adds the objects as a group.

Args:
factories: Methods for producing independent copies of an item.
*factories: Methods for producing independent copies of an item.

Raises:
AssertionError: The factories produce items not equal to the others,
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/testing/logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def assert_logs(
can be done beyond these simple asserts.

Args:
matches: Each of these is checked to see if they match, as a substring,
*matches: Each of these is checked to see if they match, as a substring,
any of the captures log messages.
count: The expected number of messages in logs. Defaults to 1. If None is passed in counts
are not checked.
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/testing/order_tester.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def add_ascending_equivalence_group(self, *group_items: Any):
Adds the objects as a group.

Args:
group_items: items making the equivalence group
*group_items: items making the equivalence group

Raises:
AssertionError: The group elements aren't equal to each other,
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/value/measurement_key_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

def test_empty_init():
with pytest.raises(TypeError, match='required positional argument'):
_ = cirq.MeasurementKey()
_ = cirq.MeasurementKey() # pylint: disable=no-value-for-parameter
with pytest.raises(ValueError, match='valid string'):
_ = cirq.MeasurementKey(None)
with pytest.raises(ValueError, match='valid string'):
Expand Down
4 changes: 2 additions & 2 deletions cirq-core/cirq/vis/heatmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ def plot(
Args:
ax: the Axes to plot on. If not given, a new figure is created,
plotted on, and shown.
kwargs: The optional keyword arguments are used to temporarily
**kwargs: The optional keyword arguments are used to temporarily
override the values present in the heatmap config. See
__init__ for more details on the allowed arguments.
Returns:
Expand Down Expand Up @@ -384,7 +384,7 @@ def plot(
Args:
ax: the Axes to plot on. If not given, a new figure is created,
plotted on, and shown.
kwargs: The optional keyword arguments are used to temporarily
**kwargs: The optional keyword arguments are used to temporarily
override the values present in the heatmap config. See
__init__ for more details on the allowed arguments.
Returns:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def create_channel(cls, address='quantum.googleapis.com:443', credentials=None,
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
kwargs (dict): Keyword arguments, which are passed to the
**kwargs (dict): Keyword arguments, which are passed to the
channel creation.

Returns:
Expand Down
2 changes: 2 additions & 0 deletions cirq-ionq/cirq_ionq/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,9 @@ def run(
return result.to_cirq_result(params=cirq.ParamResolver(param_resolver))
else:
sim_result = cast(results.SimulatorResult, result)
# pylint: disable=unexpected-keyword-arg
return sim_result.to_cirq_result(params=cirq.ParamResolver(param_resolver), seed=seed)
# pylint: enable=unexpected-keyword-arg
Comment on lines +113 to +115
Copy link
Collaborator

Choose a reason for hiding this comment

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

why is this unexpected?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

AFAICT it's a false positive from pylint. I don't know how it tries to infer the type and figure out what args are allowed, and various things I tried didn't help. We could also disable this pylint check entirely since it's probably better handled by mypy (similar to the not-callable check).


def sampler(self, target: Optional[str] = None, seed: cirq.RANDOM_STATE_OR_SEED_LIKE = None):
"""Returns a `cirq.Sampler` object for accessing the sampler interface.
Expand Down
1 change: 0 additions & 1 deletion dev_tools/conf/.pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ enable=
missing-raises-doc,
mixed-indentation,
mixed-line-endings,
not-callable,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why was this removed ?

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 think this is better handled by mypy, because it's an actual type-checker that can tell if something is callable. pylint relies on heuristics to figure out if something is callable and was producing false positives (@Strilanc filed an issue about this upstream: pylint-dev/pylint#2562).

no-value-for-parameter,
nonexistent-operator,
not-in-loop,
Expand Down
23 changes: 15 additions & 8 deletions dev_tools/pylint_copyright_checker_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

from astroid import parse
from pylint.testutils import CheckerTestCase, Message
from pylint.testutils import CheckerTestCase, MessageTest

from dev_tools.pylint_copyright_checker import CopyrightChecker

Expand All @@ -27,42 +27,49 @@ def test_missing_copyright(self) -> None:
r"""Report message when no copyright notice at the beginning of a file."""
node = parse("import os")
with self.assertAddsMessages(
Message(
MessageTest(
msg_id='wrong-or-nonexistent-copyright-notice',
line=1,
col_offset=0,
),
):
self.checker.process_module(node)

def test_wrong_copyright(self) -> None:
r"""Report message when the copyright notice is incorrect."""
node = parse("# Copyright 2021 Someone else")
comment = "# Copyright 2021 Someone else"
node = parse(comment)
with self.assertAddsMessages(
Message(
MessageTest(
msg_id='wrong-or-nonexistent-copyright-notice',
line=1,
col_offset=comment.index("Someone"),
),
):
self.checker.process_module(node)

def test_shorter_copyright(self) -> None:
r"""Report message when the copyright notice is incorrect."""
node = parse("# Copyright 2021 The")
comment = "# Copyright 2021 The"
node = parse(comment)
with self.assertAddsMessages(
Message(
MessageTest(
msg_id='wrong-or-nonexistent-copyright-notice',
line=1,
col_offset=len(comment),
),
):
self.checker.process_module(node)

def test_longer_copyright(self) -> None:
r"""Report message when the copyright notice is incorrect."""
node = parse("# Copyright 2021 The Cirq Developers and extra")
comment = "# Copyright 2021 The Cirq Developers and extra"
node = parse(comment)
with self.assertAddsMessages(
Message(
MessageTest(
msg_id='wrong-or-nonexistent-copyright-notice',
line=1,
col_offset=comment.index(" and extra"),
),
):
self.checker.process_module(node)
Expand Down
2 changes: 1 addition & 1 deletion dev_tools/requirements/deps/pylint.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# for linting

pylint~=2.6.0
pylint~=2.13.0
5 changes: 2 additions & 3 deletions dev_tools/shell_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def run_cmd(
"""Invokes a subprocess and waits for it to finish.

Args:
cmd: Components of the command to execute, e.g. ["echo", "dog"].
*cmd: Components of the command to execute, e.g. ["echo", "dog"].
out: Where to write the process' stdout. Defaults to sys.stdout. Can be
anything accepted by print's 'file' parameter, or None if the
output should be dropped, or a TeeCapture instance. If a TeeCapture
Expand All @@ -168,7 +168,6 @@ def run_cmd(
abbreviate_non_option_arguments: When logging to stderr, this cuts off
the potentially-huge tail of the command listing off e.g. hundreds
of file paths. No effect if log_run_to_stderr is not set.

**kwargs: Extra arguments for asyncio.create_subprocess_shell, such as
a cwd (current working directory) argument.

Expand Down Expand Up @@ -261,7 +260,7 @@ def output_of(*cmd: Optional[str], **kwargs) -> str:
"""Invokes a subprocess and returns its output as a string.

Args:
cmd: Components of the command to execute, e.g. ["echo", "dog"].
*cmd: Components of the command to execute, e.g. ["echo", "dog"].
**kwargs: Extra arguments for asyncio.create_subprocess_shell, such as
a cwd (current working directory) argument.

Expand Down
6 changes: 3 additions & 3 deletions examples/hhl.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def _decompose_(self, qubits):
qubits = list(qubits)
memory = qubits.pop()
for i, qubit in enumerate(qubits):
yield cirq.ControlledGate(self.U ** (2 ** i))(qubit, memory)
yield cirq.ControlledGate(self.U ** (2**i))(qubit, memory)


class EigenRotation(cirq.Gate):
Expand Down Expand Up @@ -200,7 +200,7 @@ def hhl_circuit(A, C, t, register_size, *input_prep_gates):
C: Algorithm parameter, see above.
t: Algorithm parameter, see above.
register_size: The size of the eigenvalue register.
input_prep_gates: A list of gates to be applied to |0> to generate the desired input
*input_prep_gates: A list of gates to be applied to |0> to generate the desired input
state |b>.

Returns:
Expand Down Expand Up @@ -286,7 +286,7 @@ def main():

# Set C to be the smallest eigenvalue that can be represented by the
# circuit.
C = 2 * math.pi / (2 ** register_size * t)
C = 2 * math.pi / (2**register_size * t)

# Simulate circuit.
print("Expected observable outputs:")
Expand Down