-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
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
Shouldn't the return type of __reversed__
be an Iterable[T]
instead of Iterator[T]
?
#13218
Comments
I don't find it overly surprising if you look at the range of things that |
It can; this also works without complaint:
(Ignoring the fact that no actual reversal takes place.) |
The reason your code works is that for loops always do the equivalent of I think the reason it's defined as returning an iterator is that generally you can't reverse a reverse iterator again, and also the default implementation (which uses just |
Previous related discussion about the behavior of reversed: #11645 It seems like there's two modes: If there's a |
Per discussion: The |
Currently the return type of
Reversible.__reversed__
is typed asIterator[T]
, which suggests that the returned instance must have both an__next__
and an__iter__
method.typeshed/stdlib/typing.pyi
Lines 446 to 448 in 0e9c9e1
However, the following code seems to work fine at runtime:
Note that
__reversed__
here returns aMyIter
instance, which has an__iter__
method, but no__next__
, i.e., it is anIterable
but not anIterator
. The Python interpreter seems to deal with that fine at runtime, i.e., it doesn't actually seem to need the__next__
method. This is slightly surprising, because the docs specify:I.e., it doesn't use the word "iterable object".
Unfortunately, the current signature of
__reversed__
means that this example does not type check: Obviously the type checker has to complain about thereturn MyIter(...)
line, becauseMyIter
is indeed only anIterable
(example on mypy playground):Now I'm wondering if the signature should actually be
def __reversed__(self) -> Iterable[int]
to lessen the requirement and match the runtime behavior?Note that simply changing the return type to
Iterable
on user side means that the return statement now type checks, but then all usages (reversed(my_iter)
) stop to type check because the type checker will no longer considerMyIter
as a validReversible
(modified example on mypy playground):The text was updated successfully, but these errors were encountered: