Dangerous behavior of list(generator)
apt.shansen at gmail.com
Thu Dec 31 21:18:55 CET 2009
On Thu, Dec 31, 2009 at 11:42 AM, Tom Machinski <tom.machinski at gmail.com>wrote:
> On Thu, Dec 31, 2009 at 1:54 AM, Peter Otten <__peter__ at web.de> wrote:
> > Somewhat related in 2.6 there's the next() built-in which accepts a
> > value. You can provide a sentinel and test for that instead of using
> > try...except:
> Thanks. This can be useful in some of the simpler cases. As you surely
> realize, to be perfectly safe, especially when the iterable can
> contain any value (including your sentinel), we must use an
> out-of-band return value, hence an exception is the only truly safe
Hmm? Just use a sentinel which /can't/ exist in the list: then its truly
safe. If the list can contain all the usual sort of sentinels (False, None,
0, -1, whatever), then just make a unique one all your own.
sentinel = object()
if next(g(), sentinel) is sentinel:
Its impossible to get a false-positive then, as nothing g() can ever produce
would ever be precisely "sentinel" (which would usually for me be some
global const if I need to do such things in multiple places).
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list