This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Empty Generator doesn't evaluate as False
Type: Stage:
Components: None Versions: Python 2.4
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: docwhat, rhettinger
Priority: normal Keywords:

Created on 2005-10-17 20:26 by docwhat, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg26614 - (view) Author: Christian Höltje (docwhat) Date: 2005-10-17 20:26
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. :-(
msg26615 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2005-10-17 20:58
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.
History
Date User Action Args
2022-04-11 14:56:13adminsetgithub: 42496
2005-10-17 20:26:20docwhatcreate