首页 > 解决方案 > 嵌套函数返回外部函数

问题描述

我有一个共同的模式,就像

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 中可能吗?

标签: pythonreturnglobal

解决方案


我正在使用Validationpycategories 分支:

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)

推荐阅读