-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Use of __iter__ and __next__ does not confer all Iterator protocol abilities #17361
Comments
Just a note that your example works fine if you change the class definition it to explicitly inherit from the ABC class MyIterator(Iterator[str]):
... |
The problem is that |
Closing per Spencer's comment |
To close the loop, these are a few examples given in the cited issue that do not work if def grouper(iterable, n, fillvalue=None):
"Collect data into non-overlapping fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
print(args)
# zip_longest is a C function and retects MyIterator due to lack of __iter__ method
return zip_longest(*args, fillvalue=fillvalue)
def sliding_window(iterable, n):
# sliding_window('ABCDEFG', 4) -> ABCD BCDE CDEF DEFG
it = iter(iterable)
sl = islice(it, n)
window = collections.deque(sl, maxlen=n)
if len(window) == n:
yield tuple(window)
for x in it:
window.append(x)
yield tuple(window) |
I've implemented a custom iterator that uses
__next__
and another object returns it from its__iter__
.mypy
correctly detects the object is iterable, butmypy
incorrectly omits other implied capabilities of the iterator protocol, such as__contains__
.From the python docs:
This is my sample code:
mypy prints
There should not be any errors printed here, because the two classes,
IteratorA
andIteratorB
are functionally equivalent.The code is value and running it produces this output:
The text was updated successfully, but these errors were encountered: