[issue34764] Improve documentation example for using iter() with sentinel value

Raymond Hettinger report at bugs.python.org
Fri Sep 21 14:56:18 EDT 2018


Raymond Hettinger <raymond.hettinger at gmail.com> added the comment:

I concur that the readline() example is problematic.  While it succeeds in showing how iter() works, the example itself is not the best way to solve that particular problem.

Here are two possible substitute examples.

1) Simple example that focuses primarily on the behavior of iter() and required little extra knowledge:


    >>> from random import randint
    >>> def roll_dice():
            return randint(1, 6) + randint(1, 6)

    >>> # roll until a seven is seen
    >>> list(iter(roll_dice, 7))
    >>> list(iter(roll_dice, 7))
    [10, 6, 5, 6, 8]

2) Practical application reading binary files in fixed-width blocks for processing with the structure module.  This also teaches how to partial() to produce an arity-zero callable suitable for use with iter().

    >>> Read fixed-width blocks from a database binary file
    >>> from functools import partial
    >>> with open('mydata.db', 'rb') as f:
    	    for block in iter(partial(f.read, 64)):
		print(parse_struct(block))

----------
nosy: +rhettinger

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue34764>
_______________________________________


More information about the Python-bugs-list mailing list