What are the uses of iter(callable, sentinel)?

Here’s a silly example I came up with:

from functools import partial
from random import randint

pull_trigger = partial(randint, 1, 6)

print('Starting a game of Russian Roulette...')
print('--------------------------------------')

for i in iter(pull_trigger, 6):
    print('I am still alive, selected', i)

print('Oops, game over, I am dead! :(')

Sample output:

$ python3 roulette.py 
Starting a game of Russian Roulette...
--------------------------------------
I am still alive, selected 2
I am still alive, selected 4
I am still alive, selected 2
I am still alive, selected 5
Oops, game over, I am dead! :(

The idea is to have a generator that yields random values, and you want to a process once a particular value has been selected. You could e.g. use this pattern in each run of a simulation that tries to determine the average outcome of a stochastic process.

Of course the process you would be modelling would likely be much more complicated under the hood than a simple dice roll…

Another example I can think of would be repeatedly performing an operation until it succeeds, indicated by an empty error message (let’s just assume here that some 3rd party function is designed like that instead of e.g. using exceptions):

from foo_lib import guess_password

for msg in iter(guess_password, ''):
    print('Incorrect attempt, details:', msg)

# protection cracked, continue...

Leave a Comment