Is it pythonic to put return after yield?

97 Views Asked by At

Consider the following code:

def some_gen():
    if some_condition:
        yield "Condition"
        return
    for ....:
        yield some_value

'return' after 'yield' hurts my eyes, is there a more "pythonic" way? (I know I could use 'else', but I'd like to avoid unnecessary nesting)

It also might cause a bit of confusion during a code review, because empty return gives None

1

There are 1 best solutions below

2
Morbotu On

I think a more pythonic way to do this is to put the if statement in another function. You are trying to use the function as a function and generator at the same time.

I would do something like this:

def some_gen():
    for ...:
        yield some_value

def some_func():
    if some_condition:
        gen.close()
        return "value"
    return next(gen)

gen = some_gen()