-
-
Notifications
You must be signed in to change notification settings - Fork 32.2k
Itertools Recipes - iter_index() silently suppresses ValueError #107208
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
Comments
Cc. @pochmann |
The "Fast path for sequences" btw has the same issue(?), as can be seen with this sequence version of your example: from collections.abc import Sequence
class AssertNoValue(Sequence):
def __init__(self, iterable, forbidden_value):
self.iterable = iterable
self.forbidden_value = forbidden_value
def __getitem__(self, index):
item = self.iterable[index]
if item == self.forbidden_value:
raise ValueError(f'Value {self.forbidden_value!r} is not allowed.')
return item
def __len__(self):
return len(self.iterable)
# Here we should get ValueError exception
# but it is being silently suppressed by iter_index()
list(iter_index(AssertNoValue('AABCADEAF', 'B'), 'A')) Granted, that's perhaps more artificial/unrealistic than an iterator raising a |
Interestingly, A more robust way to distinguish between the two cases would be to provide a more refined exception class as was done for
|
The proposal to add Unless someone with more social capital steps forward to champion |
…ythongh-108835) (cherry picked from commit f373c6b) Co-authored-by: Raymond Hettinger <[email protected]> pythongh-107208: iter_index now supports "stop" and no longer swallows ValueError
Uh oh!
There was an error while loading. Please reload this page.
Documentation
In Itertools Recipes there is a bug in the
iter_index()
function. The function silently suppressesValueError
exception raised by a generator given to the argumentiterable
.The bug was introduced by this pull request: gh-102088 Optimize iter_index itertools recipe #102360
Commit: 148bde6
Code to reproduce the bug:
Complete notebook reproducing the bug:
https://github.com/vbrozik/python-ntb/blob/main/problems_from_forums/2023-07-24_iter_index.ipynb
Possible solutions which come to my mind:
ValueError
inside theiter_index()
functionoperator.indexOf()
should useValueError
Note: I already mentioned the bug in the package
more-itertools
which inherited it:Update recipes.iter_index to match CPython PR 102360 #690
Linked PRs
The text was updated successfully, but these errors were encountered: