Dangerous behavior of list(generator)

Tom Machinski tom.machinski at gmail.com
Fri Jan 1 01:28:09 CET 2010

On Thu, Dec 31, 2009 at 12:18 PM, Stephen Hansen <apt.shansen at gmail.com> wrote:
> 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).
> --S

That's not a bad idea. Another nice feature is support for callable
"default" values; it would make several new things easier, including
raising an exception when you really want that (i.e. if not finding a
single element is truly exceptional).

 -- Tom

More information about the Python-list mailing list