On Fri, Oct 26, 2012 at 4:12 PM, Devin Jeanpierre <jeanpierr...@gmail.com>wrote:
> > For loops are pythonic. You can do this in Python today: > > client = StrictRedis() > for profile_id in iter(lambda: client.spop("profile_ids"), None): > pass > > I would like a better iter(), rather than a better while loop. It is > irritating to pass in functions that take arguments, and it is > impossible to, say, pass in functions that should stop being iterated > over when they return _either_ a None or a, say, False. > You can kind of do this by creating a class implementing __eq__ and passing that in as the sentinal to the iter method. class FlexibleEquality(object): def __init__(self, *candidates): self.candidates = candidates def __eq__(self, other): return any(other == candidate for candidate in self.candidates) client = StrictRedis() for profile_id in iter(lambda: client.spop("profile_ids"), FlexibleEquality(False, None)): pass But this is yucky. I'd much rather have something a bit more clear to the reader. The above is somewhat convoluted. I would far prefer for "while EXPR as VAR" to run through the results of EXPR as an iterable and continue the loop if any of the values in the iterable is truthy, maybe passing only the first value of the iterable to VAR. Gives maximum flexibility with the cleanest resulting code. >>> client.spop("profile_ids") # conditional succeeds, '123' passed to profile_id '123', True >>> client.spop("profile_ids") # conditional succeeds, '' passed to profile_id '', True >>> client.spop("profile_ids") # conditional fails '', False Dan
-- http://mail.python.org/mailman/listinfo/python-list