嵌套函数返回外部函数



我有一个类似的常见模式

def f(x):
if x.type == 'Failure':
# return `x` immediately without doing work
return x
else:
# do stuff with x...
return x

我想把if/else模式抽象成一个独立的函数。但是,当从f内部调用该函数时,我希望该函数能立即从f返回。否则,它应该只将x返回到f内部的值以进行进一步处理。类似的东西

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

这在Python中可能吗?

我正在使用pycategories:分支中的Validation

def fromSuccess(fn):
"""
Decorator function. If the decorated function
receives Success as input, it uses its value.
However if it receives Failure, it returns
the Failure without any processing.
Arguments:
fn :: Function
Returns:
Function
"""
def wrapped(*args, **kwargs):
d = kwargs.pop('d')
if d.type == 'Failure':
return d
else:
kwargs['d'] = d.value
return fn(*args, **kwargs)
return wrapped
@fromSuccess
def return_if_failure(d):
return d * 10
return_if_failure(d = Failure(2)), return_if_failure(d = Success(2))
>>> (Failure(2), 20)

最新更新