【问题标题】:nested function returning outer function嵌套函数返回外部函数
【发布时间】:2018-11-08 00:36:03
【问题描述】:

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

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

【问题讨论】:

  • 您是在问这是否有可能,或者是否有在 Python 中执行此操作的快捷方式?自己放入逻辑当然是完全可能且相对容易的,例如通过从 g 返回一个元组而不是单个值,并使用元组中的一个值来告诉 f 是否立即返回。这只是你如何做到这一点的一个例子,但它不一定是 Python 中内置的东西。
  • @RandomDavis 我想抽象,所以我可以在任何地方使用g,而无需更改仅处理x.value 的代码。我认为装饰器功能可能是一个很好的解决方案,但我欢迎其他选择。是的,实际的解决方案会比普通的 yesno 更好!
  • 我怀疑你能做到这一点,而且这似乎是一个坏主意。函数不应假设调用者将如何使用其结果。
  • 我能想到的唯一可以做到这一点的语言是 Common Lisp,使用扩展为 RETURN 表达式的宏。即使这样,它的行为也取决于它的使用位置,因为RETURN 将退出最近的封闭循环或函数。
  • 在Scheme中,您可以使用带有第二个参数的函数来执行此操作,在您想要进行全局返回的情况下继续调用。

标签: python return global


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-09-14
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2012-11-20
    相关资源
    最近更新 更多