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

Add Y091: Protocol method arg should not be pos-or-kw #442

Merged
merged 22 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ New error codes:
* Introduce Y060, which flags redundant inheritance from `Generic[]`.
* Introduce Y061: Do not use `None` inside a `Literal[]` slice.
For example, use `Literal["foo"] | None` instead of `Literal["foo", None]`.
* Introduce Y058: Protocol method parameters should not be positional-or-keyword.
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved

Other changes:
* The undocumented `pyi.__version__` and `pyi.PyiTreeChecker.version`
Expand Down
2 changes: 2 additions & 0 deletions ERRORCODES.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ The following warnings are currently emitted by default:
| Y059 | `Generic[]` should always be the last base class, if it is present in a class's bases tuple. At runtime, if `Generic[]` is not the final class in a the bases tuple, this [can cause the class creation to fail](https://github.com/python/cpython/issues/106102). In a stub file, however, this rule is enforced purely for stylistic consistency.
| Y060 | Redundant inheritance from `Generic[]`. For example, `class Foo(Iterable[_T], Generic[_T]): ...` can be written more simply as `class Foo(Iterable[_T]): ...`.<br><br>To avoid false-positive errors, and to avoid complexity in the implementation, this check is deliberately conservative: it only looks at classes that have exactly two bases.
| Y061 | Do not use `None` inside a `Literal[]` slice. For example, use `Literal["foo"] \| None` instead of `Literal["foo", None]`. While both are legal according to [PEP 586](https://peps.python.org/pep-0586/), the former is preferred for stylistic consistency.
| Y062 | Protocol methods should not be positional-or-keyword. Usually, a positional-only argument is better.
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved

## Warnings disabled by default

Expand All @@ -79,3 +80,4 @@ recommend only using `--extend-select`, never `--select`.
| Code | Description
|------|------------
| Y090 | `tuple[int]` means "a tuple of length 1, in which the sole element is of type `int`". Consider using `tuple[int, ...]` instead, which means "a tuple of arbitrary (possibly 0) length, in which all elements are of type `int`".
>>>>>>> upstream/main
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved
38 changes: 30 additions & 8 deletions pyi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import argparse
import ast
import contextlib
import logging
import re
import sys
Expand Down Expand Up @@ -968,6 +969,7 @@ def __init__(self, filename: str) -> None:
self.string_literals_allowed = NestingCounter()
self.in_function = NestingCounter()
self.in_class = NestingCounter()
self.in_protocol = NestingCounter()
self.visiting_arg = NestingCounter()

def __repr__(self) -> str:
Expand Down Expand Up @@ -1592,23 +1594,33 @@ def _check_class_bases(self, bases: list[ast.expr]) -> None:
self.error(Generic_basenode, Y060)

def visit_ClassDef(self, node: ast.ClassDef) -> None:
class_is_protocol = class_is_typeddict = False
for base in node.bases:
if _is_Protocol(base):
class_is_protocol = True
if _is_TypedDict(base):
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved
class_is_typeddict = True

if node.name.startswith("_") and not self.in_class.active:
for base in node.bases:
if _is_Protocol(base):
self.protocol_defs[node.name].append(node)
break
if _is_TypedDict(base):
self.class_based_typeddicts[node.name].append(node)
break
if class_is_protocol:
self.protocol_defs[node.name].append(node)
if class_is_typeddict:
self.class_based_typeddicts[node.name].append(node)

old_class_node = self.current_class_node
self.current_class_node = node
with self.in_class.enabled():
with contextlib.ExitStack() as stack:
stack.enter_context(self.in_class.enabled())
if class_is_protocol:
stack.enter_context(self.in_protocol.enabled())
self.generic_visit(node)
self.current_class_node = old_class_node

self._check_class_bases(node.bases)

JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved
self.check_class_pass_and_ellipsis(node)

def check_class_pass_and_ellipsis(self, node: ast.ClassDef) -> None:
# empty class body should contain "..." not "pass"
if len(node.body) == 1:
statement = node.body[0]
Expand Down Expand Up @@ -1987,6 +1999,10 @@ def check_self_typevars(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> N
return_annotation=return_annotation,
)

def check_arg_kinds(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
for pos_or_kw in node.args.args[1:]: # exclude "self"
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved
self.error(pos_or_kw, Y058.format(arg=pos_or_kw.arg, method=node.name))

def _visit_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
with self.in_function.enabled():
self.generic_visit(node)
Expand All @@ -2010,6 +2026,8 @@ def _visit_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:

if self.in_class.active:
self.check_self_typevars(node)
if self.in_protocol.active:
self.check_arg_kinds(node)
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved

def visit_arg(self, node: ast.arg) -> None:
if _is_NoReturn(node.annotation):
Expand Down Expand Up @@ -2233,6 +2251,10 @@ def parse_options(options: argparse.Namespace) -> None:
"class would be inferred as generic anyway"
)
Y061 = 'Y061 None inside "Literal[]" expression. Replace with "{suggestion}"'
Y062 = (
'Y058 Argument "{arg}" to protocol method "{method}" should not be positional-or-keyword'
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved
" (suggestion: make it positional-only)"
)
Y090 = (
'Y090 "{original}" means '
'"a tuple of length 1, in which the sole element is of type {typ!r}". '
Expand Down
6 changes: 6 additions & 0 deletions tests/protocol_arg.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from typing import Protocol

class P(Protocol):
def method1(self, arg: int) -> None: ... # Y062 Argument "arg" to protocol method "method1" should not be positional-or-keyword (suggestion: make it positional-only)
def method2(self, arg: str, /) -> None: ...
def method3(self, *, arg: str) -> None: ...
Loading