from __future__ import * 24.11.2003

2003-11-24

for loops and empty iterables

Just van Rossum and I were discussing the for:else:, while:else: and try:else: syntax on the MacPythonChannel this morning (morning for me, at least). I'm not sure if this is sufficiently covered elsewhere, but here is the pattern I use to check for empty iterables:

class NoValue:
    """A unique placeholder, since None is sometimes used in iterables"""

def doesSomethingWithIterable(iterable):
    x = NoValue
    for x in iterable:
        pass # something useful could go here ;)
    else:
        if x is NoValue:
            pass # do something because iterable was empty
        else:
            pass # do something because iterable was not empty
posted at 11:11:44    #    comment []    trackback []
November
MoTuWeThFrSaSu
      1 2
3 4 5 6 7 8 9
10111213141516
17181920212223
24252627282930
Oct Dec

Bob's Rants

XML-Image Letterimage

© 2003-2004, Bob Ippolito