简体   繁体   中英

How to handle a StopIteration exception while dealing with generator

I'm working with a generator and I have the code below. I'm a little confused about its logic.

The generator in the function works fine as long as there is a 'False' at the end. Removing it causes a StopIteration exception when running the function.

Can anybody explain me the role of False here?

>>> def some(coll, pred= lambda x:x)
...    return next((True for item in coll if pred(item)),False)
... 
>>> some([0,'',False])
False
>>> def some(coll, pred= lambda x:x):
...     return next((True for item in coll if pred(item)))
...
>>> some([0,'',False])
Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    some([0,'',False])
  File "<pyshell#63>", line 2, in some
    return next((True for item in coll if pred(item)))
StopIteration

You are passing in a default value for the next() function to return if the generator expression raises a StopIteration exception. The False is the default value returned here:

Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

Raising StopIteration is how iterators communicate that they are done and can no longer be used to produce results. Generators are a specialised type of iterator.

You don't have to pass in False ; any valid Python value will do. If you omit the default argument, you can also omit the generator parenthesis:

next(True for item in coll if pred(item))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM