[ python-Bugs-1328959 ] Empty Generator doesn't evaluate as False

SourceForge.net noreply at sourceforge.net
Mon Oct 17 22:58:11 CEST 2005


Bugs item #1328959, was opened at 2005-10-17 15:26
Message generated for change (Comment added) made by rhettinger
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1328959&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: None
Group: Python 2.4
>Status: Closed
>Resolution: Invalid
Priority: 5
Submitted By: Christian Höltje (docwhat)
Assigned to: Nobody/Anonymous (nobody)
Summary: Empty Generator doesn't evaluate as False

Initial Comment:
The following code doesn't work correctly if the
function "generator()" doesn't have any values.

if generator():
  print "This should only happen when the generator
runs yield"
  print " but it is always true, even if the generator
is empty"
else:
  print "this is the expected path when the generator
is empty"

The workaround is:

try:
  generator().next()
  print "this is the true case"
except StopIteration:
  print "this is the false case"

This means that generators are not transparent and they
don't behave as expected (like a list or tuple).

I've been bitten by this enough that I am unhappy. :-(

----------------------------------------------------------------------

>Comment By: Raymond Hettinger (rhettinger)
Date: 2005-10-17 15:58

Message:
Logged In: YES 
user_id=80475

Your unhappiness is predicated on an invalid set of
assumptions.  For most generators, it is not possible to
know in advance whether the iterator will raise
StopIteration on the next call.

Also, Guido has pronounced that generators (like most
objects) will always evaluate to True.

----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1328959&group_id=5470


More information about the Python-bugs-list mailing list