I have a common pattern that goes like
def f(x):
if x.type == 'Failure':
# return `x` immediately without doing work
return x
else:
# do stuff with x...
return x
I would like to abstract the if/else pattern into a stand alone function. However I want that function, when called from inside f, to return from f immediately. Else it should just return x to a value inside f for further processing. Something like
def g(x):
if x.type == 'Failure':
global return x
else:
return x.value
def f(x):
x_prime = g(x) # will return from f
# if x.type == 'Failure'
# do some processing...
return x_prime
Is this possible in Python?
ginstead of a single value, and using one of the values in the tuple to tellfto return immediately or not. That's just one example of how you could do it, but it's not necessarily something built-in in Python.geverywhere without changing code that only handlesx.value. I'm thinking a decorator function could be a neat solution, but I welcome other alternatives. Yes, an actual solution would be better than a plainyesorno!RETURNexpression. And even then, its behavior would depend on where it's used, becauseRETURNwill exit the closest enclosing loop or function.