Feature suggestion -- return if true

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Thu Apr 21 12:13:43 CEST 2011


Am 13.04.2011 01:06, schrieb Ethan Furman:

> --> def func():
> --> var1 = something()
> --> var2 = something_else('this')
> --> return? var1.hobgle(var2)
> --> var3 = last_resort(var1)
> --> return var3.wiglat(var2)

This makes me think of a decorator which can mimic the wantend behaviour:

def getfirst(f):
     from functools import wraps
     @wraps(f)
     def func(*a, **k):
         for i in f(*a, **k):
             if i: return i
     return func

# [BTW: a kind of "return decorator" would be nice here ;-)]

@getfirst
def func():
     var1 = something()
     var2 = something_else('this')
     yield var1.hobgle(var2)
     var3 = last_resort(var1)
     yield var3.wiglat(var2)
     yield "Even that did not work."

This has the advantage of being flexible about which condition to 
evaluate: maybe the func does return tuples of which only the 2nd part 
is relevant concerning the check. Then just do


def getfirst(f):
     from functools import wraps
     @wraps(f)
     def func(*a, **k):
         for i in f(*a, **k):
             if i[1]: return i
     return func

@getfirst
def func():
     var1 = something()
     var2 = something_else('this')
     yield "first try", var1.hobgle(var2)
     var3 = last_resort(var1)
     yield "second try", var3.wiglat(var2)
     yield "default value", "Even that did not work."


Disclaimer: Untested, but you should get the idea.

Thomas



More information about the Python-list mailing list