[ty] Infer implicit type of cls in __new__ methods#22584
Conversation
Typing conformance resultsNo changes detected ✅ |
|
|
| Lint rule | Added | Removed | Changed |
|---|---|---|---|
unresolved-attribute |
45 | 0 | 2 |
invalid-argument-type |
8 | 0 | 1 |
invalid-assignment |
6 | 0 | 0 |
invalid-return-type |
4 | 0 | 2 |
possibly-missing-attribute |
4 | 0 | 1 |
unused-ignore-comment |
0 | 5 | 0 |
invalid-await |
2 | 0 | 0 |
invalid-attribute-access |
1 | 0 | 0 |
| Total | 70 | 5 | 6 |
| def __new__(cls) -> Self: | ||
| return super().__new__(cls) | ||
| # error: [invalid-return-type] | ||
| return type(cls) |
There was a problem hiding this comment.
The point of this test is that the usage of Self above should return a diagnostic, but it seems mildly confusing to introduce another unrelated diagnostic. Here's a version that doesn't introduce a diagnostic:
def __new__(cls, name, bases, dct) -> Self:
return cls(name, bases, dct)|
The new ecosystem diagnostics here are technically false positives, but they are also emitted by pyright and strict-mode mypy, and they look expected, in that it's known that we won't see attributes dynamically attached in |
self in __new__ methodscls in __new__ methods
|
It looks like the from collections import namedtuple
from typing import NamedTuple, Self
class Foo(NamedTuple):
x: int
class Bar(Foo):
def __new__(cls) -> "Bar":
return super().__new__(cls, x=42) # error[invalid-return-type] "Return type does not match returned value: expected `Bar`, found `Foo`"
class Bar2(Foo):
def __new__(cls) -> Self:
return super().__new__(cls, x=42) # error[invalid-return-type] "Return type does not match returned value: expected `Self@__new__`, found `Foo`"
Baz = namedtuple("Baz", "x y")
class Spam(Baz):
def __new__(cls) -> "Spam":
return super().__new__(cls, x=42, y=56) # error[invalid-return-type] "Return type does not match returned value: expected `Spam`, found `Baz`"
class Spam2(Baz):
def __new__(cls) -> Self:
return super().__new__(cls, x=42, y=56) # error[invalid-return-type] "Return type does not match returned value: expected `Self@__new__`, found `Baz`"I think the return type we synthesize for these methods changed in 3e02994. We need to infer these methods as returning |
I wouldn't necessarily characterise setting an attribute in So I'd love to support recognising implicit instance attributes set in |
|
I opened astral-sh/ty#2522 to track the new NamedTuple false positives |
Summary
Resolves astral-sh/ty#2489.