MacPython Logo from __future__ import *

Kailash and Friends Kailash Kher Kaipa

online mp3 Anoice albums buy Amund Maarud albums online Asia online CD Andy M. Stewart buy tracks Axis online Astral Rising A Beautiful Machine download CD Aereda buy tracks Aksent online tracks Absidia Atrium Carceri A Beautiful Machine Absolum buy CD Aryan Wind and Brumalis and Valhalla Saints online music Atomsmasher download albums AK1200 download music Angelzoom online CD Arturo Mantovani and his Orchestra buy music 16 buy tracks Ashtorath online CD Aimee Mann buy music Anael And Bradfield buy mp3 Autumnblaze download mp3 Aggrolites download CD Arj Snoek buy albums Ada buy CD Aalto Andy With Rama West A Beautiful Machine Absolum online tracks Asura albums online Albert Lee 4 Non Blondes A Beautiful Machine Absolum download albums Andrew Lloyd Webber and Ar Rahman online music African Head Charge download mp3 Amber Asylum online music Analena online music ANTIX feat ROB SALMON A.R. Rahman A Beautiful Machine Absolum online tracks African Blackwood buy mp3 Axis buy mp3 Alan Menken buy music Amoebic Dysentery buy Alph Secakuku A Beautiful Machine albums download Albita online Amparo Ochoa A Beautiful Machine download tracks Andy Partridge and Harold Budd download tracks Anubian Lights Alient Project A Beautiful Machine Absolum buy albums Antonio Forcione download CD Ali G Indahouse online mp3 Art and Jazz Messengers Blakey download Arab Strap A Beautiful Machine online albums Adema buy Agua de Annique A Beautiful Machine buy CD Avalanches download tracks Acroma Andi Deris A Beautiful Machine Absolum download tracks American Steel download albums Amanda Perez online 999 A Beautiful Machine download mp3 Arild Andersen download CD American Steel buy tracks Absolute Beginner download tracks Anubi online albums Ancient Wisdom online A Verse Unsung A Beautiful Machine buy music Aghast Andromeda Island A Beautiful Machine Absolum download Arlo Guthrie A Beautiful Machine online mp3 Aavepyora online albums Achillea buy Andrew Bird A Beautiful Machine buy music Alexey Aigui and Ensemble 4'33'' albums buy Abbey Lincoln and Archie Shepp download albums Archive download CD A Guy Called Gerald feat. D.S. download music Al Di Meola online music Abigail download music Angel Witch online music Adelaide

2005-06-14

Python iterators and sentinel values

Filed under: python — bob @ 11:29 am

A little known feature of PEP 234: Iterators (implemented in Python 2.1 and later) is the alternate form:

iter(callable, sentinel)

This form creates an iterator out of any callable, and will stop when an exception is raised or the sentinel value is returned by the callable. Additionally, raising StopIteration will stop the iteration as with a normal iterator. A sentinel value is a special value that indicates the end of a sequence. This can be any value, but the most commonly useful values are likely to be None, 0, or ''.

I haven't seen much code in the wild that takes advantage of this form of iter, but an excellent usage would be to replace this common idiom:

while True:
    data = fileobj.read(BLOCKSIZE)
    if not data:
        break
    # do something with data here

Using the sentinel form of iter, it can be rewritten as an iterator with more obvious control flow:

for data in iter(lambda: fileobj.read(BLOCKSIZE), ''):
    # do something with data here

Of course, nobody likes a lambda, but you could wrap this up as a little utility function, or you could wait for PEP 309: Partial Function Application (on the standards track, will be in Python 2.5). With partial it would look like this:

for data in iter(partial(fileobj.read, BLOCKSIZE), ''):
    # do something with data here

5 Comments »

  1. Thanks for the post, very informative.

    I still don’t have my head wrapped around Ruby’s code blocks, but this looks similar to some of the examples I’ve seen.

    Comment by Matt — 2005-06-15 @ 11:52 am

  2. Until PEP 309 is implemented, functions as the one in this message can be used:

    Comment by Christos Georgiou — 2005-06-24 @ 4:28 am

  3. This form creates an iterator out of any callable, and will stop when an exception is raised…

    At first I was excited by this, but testing on 2.4 reveals that it’s not true, or at least that it’s misleading. Consider:

    >>> tuple(iter(range(5).pop, None))
    Traceback (most recent call last):
    File "“, line 1, in ?
    IndexError: pop from empty list

    Based on your advice, I had expected the IndexError to be caught by the iterator and reraised as a StopIteration. That would be convenient but perhaps in some cases confusing; that’s not how it works. I guess you really meant to say what you said in the next sentence, that raising StopIteration would stop the iteration. That’s true but a bit trivial. Cheers!

    Comment by Jess Austin — 2005-07-12 @ 4:00 pm

  4. I didn’t say that exceptions would be converted into StopIteration, I just said the iteration will stop

    Comment by Bob Ippolito — 2005-07-12 @ 4:06 pm

  5. As with any uncaught exception, all execution will stop, not just the iteration. (maybe that’s what you meant?) Only a StopIteration will be caught by the iteration context. Cheers!

    Comment by Jess Austin — 2005-07-12 @ 4:32 pm

RSS feed for comments on this post.

Leave a comment

WP-Hashcash: protecting you from spam.

Powered by WordPress