-
Notifications
You must be signed in to change notification settings - Fork 1.6k
[ty] Minor fixes to Protocol tests
#20347
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
Conversation
| # this is fine: the call succeeds at runtime since the second argument is optional | ||
| reveal_type(len(SecondOptionalArgument())) # revealed: Literal[0] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we could consider emitting a diagnostic on the definition of __len__ itself here (but that should be a disabled-by-default lint rule, IMO!), but I see no reason why we should emit a diagnostic at the len() call itself here. SecondOptionalArgument is a subtype of Sized.
| class CanIndex(Protocol[T]): | ||
| def __getitem__(self, index: int) -> T: ... | ||
| def __getitem__(self, index: int, /) -> T: ... |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The intent of this test is that list[str] should be a subtype of CanIndex; below, an instance of list[str] is passed into takes_in_protocol. But as written, list[str] is not a subtype of CanIndex, since all parameters of list.__getitem__ are positional-only
| Because method members are always looked up on the meta-type of an object when testing assignability | ||
| and subtyping, we understand that `IterableClass` here is a subtype of `Iterable` even though | ||
| `Foo.__iter__` resolves to a type with the wrong signature: | ||
|
|
||
| ```py | ||
| from typing import Iterator, Iterable | ||
| from ty_extensions import static_assert, is_subtype_of, TypeOf | ||
|
|
||
| class Meta(type): | ||
| def __iter__(self) -> Iterator[int]: | ||
| yield from range(42) | ||
|
|
||
| class IterableClass(metaclass=Meta): | ||
| def __iter__(self) -> Iterator[str]: | ||
| yield from "abc" | ||
|
|
||
| static_assert(is_subtype_of(TypeOf[IterableClass], Iterable[int])) | ||
| ``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A missing test that demonstrates another reason why it's important that dunder methods especially must be looked up on the meta-type when determining protocol subtyping/assignability
Co-authored-by: Carl Meyer <carl@astral.sh>
No description provided.