Skip to content

itertools.tee lookahead/peek example doesn't work #126701

Closed
@yggdr

Description

Documentation

In the tee documentation a method for making tee-iterators peekable is mentioned:

def lookahead(tee_iterator):
     "Return the next value without moving the input forward"
     [forked_iterator] = tee(tee_iterator, 1)
     return next(forked_iterator)

iterator = iter('abcdef')
[iterator] = tee(iterator, 1)   # Make the input peekable
next(iterator)                  # Move the iterator forward; prints 'a'
lookahead(iterator)             # Check next value; prints 'b'
next(iterator)                  # Continue moving forward; supposedly also prints 'b', but prints 'c' instead!

Tested on versions 3.13.0, 3.11.10, 3.9.18 (and 2.7.18 for a laugh).

#123884 seems to be the source of the error, and it is indeed working correctly on 3.14@4f3253a0ccf3a512c497f779e4a6db2656c75844. But the documentation for older version should be updated, as following recipes from the official docs that don't work on the version the docs are for makes debugging a nightmare.

The docs might also want to mention a possible workaround in the form of _, iterator = tee(iterator, 2), as only the first copy from tee seems to be afflicted by the bug. At least that is my reading of its description, and it seems to work in a quick test.

Metadata

Assignees

Labels

docsDocumentation in the Doc dir

Type

No type

Projects

  • Status

    Todo

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions