Skip to content

Itertools Recipes - iter_index() silently suppresses ValueError #107208

@vbrozik

Description

@vbrozik

Documentation

In Itertools Recipes there is a bug in the iter_index() function. The function silently suppresses ValueError exception raised by a generator given to the argument iterable.

The bug was introduced by this pull request: gh-102088 Optimize iter_index itertools recipe #102360
Commit: 148bde6

Code to reproduce the bug:

def assert_no_value(iterable, forbidden_value):
    """Pass the iterable but raise ValueError if forbidden_value is found."""
    for item in iterable:
        if item == forbidden_value:
            raise ValueError(f'Value {forbidden_value!r} is not allowed.')
        yield item

# Here we should get ValueError exception
# but it is being silently suppressed by iter_index()
list(iter_index(assert_no_value('AABCADEAF', 'B'), 'A'))

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:

  • revert the commit 148bde6
  • check the value of ValueError inside the iter_index() function
  • open discussion to determine whether operator.indexOf() should use ValueError

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

Metadata

Metadata

Assignees

Labels

docsDocumentation in the Doc dir

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions