嵌套函数返回外部函数[python]

时间:2018-11-08 00:36:04

标签: python return global

我有一个类似的常见模式

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

1 个答案:

答案 0 :(得分:1)

我正在使用my branch的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)