是否有像 x = y 或 return 这样的 Python 单行成语?

Is there a Python one-line idiom like x = y or return?

return early 模式是嵌套 if/else 语句的替代方案。在 Ruby 中,这有时被视为一行:

# Ruby
x = f(y) or return APPROPRIATE_ERROR

如果or左边的表达式是假的,它会return。

除了

,还有Python方法吗?
# Python
x = f(y)
if not x:
    return APPROPRIATE_ERROR

使用 := 运算符,您的 Python 示例可以更简洁一些。

if not (x := f(y)):
    return APPROPRIATE_ERROR

在此之后,假设不满足条件,您可以正常使用 x

这在很多地方都很有用。我发现它在编写 lambdas 时特别有用,我不能在其中进行正常赋值,但又不想重复重新计算值。

这样做在语法上是正确的

...
if not (x := f(y)): return APPROPRIATE_ERROR
...

一般不推荐作为标准款,但喜欢的可以选择

我添加这个只是为了好玩(并详细说明我的评论)。 您可以从 here 的第二个答案中采用 hacky 装饰器方法。为了完整起见:

class ReturnValue(Exception):
    def __init__(self, value):
        Exception.__init__(self)
        self.value = value


def enable_ret(func):
    def decorated_func(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except ReturnValue as exc:
            return exc.value

    return decorated_func


def ret(value):
    raise ReturnValue(value)

现在,请记住 if 和 while 块是范围规则中的例外。具体来说,在 ifwhile 块中定义的变量在函数范围内可用。如果我正确理解你的问题,你现在可以像这样使用它:

@enable_ret
def testfunc(x):
    # Return None if y is false
    ret(None) if not (y := x) else 0

    # Otherwise we continue (and can access y) here
    print(y)
    return 1

请不要这样做:)