views:

121

answers:

5

I have a for loop that checks a series of conditions. On each iteration, it should yield output for only one of the conditions. The final yield is a default, in case none of the conditions are true. Do I have to put a continue after each block of yields?

def function():
    for ii in aa:
       if condition1(ii):
           yield something1
           yield something2
           yield something3
           continue

       if condition2(ii):
           yield something4
           continue

       #default
       yield something5
       continue
+7  A: 

Instead of using the continue statement I would suggest using the elif and else statments:

def function():
    for ii in aa:
       if condition1(ii):
           yield something1
           yield something2
           yield something3

       elif condition2(ii):
           yield something4

       else: #default
           yield something5

This seems much more readable to me

flashk
+3  A: 

NO, yield doesn't imply continue, it just starts at next line, next time. A simple example demonstrates that

def f():
    for i in range(3):
        yield i
        print i,

list(f())

This prints 0,1,2 but if yield continues, it won't

Anurag Uniyal
+1  A: 

continue skips the remaining code block, but the code block after yield is executed when next() is called again on the generator. yield acts like pausing execution at certain point.

Imran
A: 

yields in Python stop execution and returning the value. When the iterator is invoked again it continues execution directly after the yield statement. For instance, a generator defined:

def function():
    yield 1
    yield 2

would return 1 then 2 sequentially. In other words, the continue is required. However, in this instance, elif and else are definitely the right tools.

Aardsquid
A: 

If the something is simple value and conditions are checks for equality, I would prefer to make this "case structure" dictionary lookup:

ii_dict={'a':('somethinga1','somethinga2','somethinga3'),'b':('somethingb1',)}
ii_default = ('somethingdefault',)
aa='abeabbacd'

def function():
    return (value
           for ii in aa
           for value in (ii_dict[ii] if ii in ii_dict else ii_default))

for something in function(): print something
Tony Veijalainen