Generator - yield break in Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

http://stackoverflow.com/questions/1704607/difference-between-yield-in-python-and-yield-in-c http://stackoverflow.com/questions/1704607/difference-between-yield-in-python-and-yield-in-c

def generate_nothing():
    return

for i in generate_nothing():
    print i

you will get a TypeError: NoneType object is not iterable. but if I add an never run yield before return, this function return what I expect.

def generate_nothing():
    if False: yield None
    return

if works but seems wired. Who has better idea?

thanks,

Answers

http://docs.python.org/2/library/exceptions.html#exceptions.StopIteration http://docs.python.org/2/library/exceptions.html#exceptions.StopIteration

For example, given a tuple (0, 1, 2, 3) I want to get overlapping pairs ((0, 1), (1, 2), (2, 3)). I could do it like so:

def pairs(numbers):
    if len(numbers) < 2:
        raise StopIteration

    for i, number in enumerate(numbers[1:]):
        yield numbers[i], number

Now pairs safely handles lists with 1 number or less.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/6395063/yield-break-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils