Skip to content

Detect __eq__ and __ne__ methods that use Any instead of object #163

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

Merged
merged 2 commits into from
Jan 31, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ Bugfixes:
* fix bug where `TypeVar`s were erroneously flagged as unused if they were only used in
a `typing.Union` subscript.

Features:
* introduce Y032 (prefer `object` to `Any` for the second argument in `__eq__` and
`__ne__` methods).

## 22.1.0

* extend Y001 to cover `ParamSpec` and `TypeVarTuple` in addition to `TypeVar`
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ currently emitted:
| Y029 | It is almost always redundant to define `__str__` or `__repr__` in a stub file, as the signatures are almost always identical to `object.__str__` and `object.__repr__`.
| Y030 | Union expressions should never have more than one `Literal` member, as `Literal[1] \| Literal[2]` is semantically identical to `Literal[1, 2]`.
| Y031 | `TypedDict`s should use class-based syntax instead of assignment-based syntax wherever possible. (In situations where this is not possible, such as if a field is a Python keyword or an invalid identifier, this error will not be raised.)
| Y032 | The second argument of an `__eq__` or `__ne__` method should usually be annotated with `object` rather than `Any`.

Many error codes enforce modern conventions, and some cannot yet be used in
all cases:
Expand Down
43 changes: 29 additions & 14 deletions pyi.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ def _is_object(node: ast.expr, name: str, *, from_: Container[str]) -> bool:
_is_TypedDict = partial(_is_object, name="TypedDict", from_=_TYPING_MODULES)
_is_Literal = partial(_is_object, name="Literal", from_=_TYPING_MODULES)
_is_abstractmethod = partial(_is_object, name="abstractmethod", from_={"abc"})
_is_Any = partial(_is_object, name="Any", from_={"typing"})


def _unparse_assign_node(node: ast.Assign | ast.AnnAssign) -> str:
Expand Down Expand Up @@ -806,25 +807,36 @@ def visit_ClassDef(self, node: ast.ClassDef) -> None:
):
self.error(statement, Y013)

def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
def _visit_method(self, node: ast.FunctionDef) -> None:
method_name = node.name
all_args = node.args

if all_args.kwonlyargs:
return

# pos-only args don't exist on 3.7
pos_only_args: list[ast.arg] = getattr(all_args, "posonlyargs", [])
pos_or_kwd_args = all_args.args
non_kw_only_args = pos_only_args + pos_or_kwd_args

# Raise an error for defining __str__ or __repr__ on a class, but only if:
# 1). The method is not decorated with @abstractmethod
# 2). The method has the exact same signature as object.__str__/object.__repr__
if (
self.in_class.active
and node.name in {"__repr__", "__str__"}
and _is_name(node.returns, "str")
and not any(_is_abstractmethod(deco) for deco in node.decorator_list)
):
all_args = node.args
# pos-only args don't exist on 3.7
pos_only_args: list[ast.arg] = getattr(all_args, "posonlyargs", [])
pos_or_kwd_args = all_args.args
kwd_only_args = all_args.kwonlyargs

if ((len(pos_only_args) + len(pos_or_kwd_args)) == 1) and not kwd_only_args:
if method_name in {"__repr__", "__str__"}:
if (
len(non_kw_only_args) == 1
and _is_name(node.returns, "str")
and not any(_is_abstractmethod(deco) for deco in node.decorator_list)
):
self.error(node, Y029)

elif method_name in {"__eq__", "__ne__"}:
if len(non_kw_only_args) == 2 and _is_Any(non_kw_only_args[1].annotation):
self.error(node, Y032.format(method_name=method_name))

def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
if self.in_class.active:
self._visit_method(node)
self._visit_function(node)

def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
Expand Down Expand Up @@ -1064,3 +1076,6 @@ def parse_options(cls, optmanager, options, extra_args) -> None:
Y029 = "Y029 Defining __repr__ or __str__ in a stub is almost always redundant"
Y030 = "Y030 Multiple Literal members in a union. {suggestion}"
Y031 = "Y031 Use class-based syntax for TypedDicts where possible"
Y032 = (
'Y032 Prefer "object" to "Any" for the second parameter in "{method_name}" methods'
)
10 changes: 10 additions & 0 deletions tests/classdefs.pyi
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
import abc
import typing
from abc import abstractmethod
from typing import Any

class Bad:
def __repr__(self) -> str: ... # Y029 Defining __repr__ or __str__ in a stub is almost always redundant
def __str__(self) -> str: ... # Y029 Defining __repr__ or __str__ in a stub is almost always redundant
def __eq__(self, other: Any) -> bool: ... # Y032 Prefer "object" to "Any" for the second parameter in "__eq__" methods
def __ne__(self, other: typing.Any) -> typing.Any: ... # Y032 Prefer "object" to "Any" for the second parameter in "__ne__" methods

class Good:
@abstractmethod
def __str__(self) -> str: ...
@abc.abstractmethod
def __repr__(self) -> str: ...
def __eq__(self, other: object) -> bool: ...
def __ne__(self, obj: object) -> int: ...

class Fine:
@abc.abstractmethod
def __str__(self) -> str: ...
@abc.abstractmethod
def __repr__(self) -> str: ...
def __eq__(self, other: Any, strange_extra_arg: list[str]) -> Any: ...
def __ne__(self, *, kw_only_other: Any) -> bool: ...

class AlsoGood(str):
def __str__(self) -> AlsoGood: ...
Expand All @@ -27,3 +35,5 @@ class FineAndDandy:

def __repr__(self) -> str: ...
def __str__(self) -> str: ...
def __eq__(self, other: Any) -> bool: ...
def __ne__(self, other: Any) -> bool: ...