PEP572 中的海象运算符示例 [英] Walrus operator example in PEP572

查看:42
本文介绍了PEP572 中的海象运算符示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PEP572 中给出的示例之一是

# Reuse a value that's expensive to compute
[y := f(x), y**2, y**3]

目前在 python 中,您必须执行以下操作之一:

currently in python, you'd have to do one of the following:

# option 1
y = f(x)
[y, y**2, y**3]

# option 2 
[f(x), f(x)**2, f(x)**3]

该示例暗示此处的选项 2 可以改进,但我从未见过比第一个选项更推荐的选项.选项 2(以及海象运营商)优于选项 1 是否有任何理由?

the example implies that option 2 here could be improved, but I have never seen that recommended over the first option. Is there ever a reason why option 2 (and therefore the walrus operator) would be better than option 1?

推荐答案

只是为了把事情说清楚:

Just to make things clear:

[y := f(x), y**2, y**3]

相当于:

y = f(x)
[y, y**2, y**3]

(f(x) 只调用一次)

但总的来说,不是这个:

but, in general, not this:

[f(x), f(x)**2, f(x)**3]

(f(x) 被调用了 3 次)

(f(x) is called three times)

因为潜在的 f() 副作用(或者潜在的不必要的计算负担,如果 f() 是一个 函数).

because of potential f() side-effects (or potential unnecessary computational burden, if f() is a pure function).

所以,一般来说,将 [f(x), f(x)**2, f(x)**3] 替换为 [y := f(x), y**2, y**3] 应该仔细检查.

So, in general, replacing [f(x), f(x)**2, f(x)**3] with [y := f(x), y**2, y**3] should be inspected carefully.

例如:

def f(x):
    print('Brooks was here.')
    return 2 * x


x = 1
y = f(x)
l1 = [y, y**2, y**3]

打印Brooks在这里.一次,同时:

l2 = [f(x), f(x)**2, f(x)**3]

将打印 Brooks was here. 三遍.当然,l1 == l2.

will print Brooks was here. three times. Of course, l1 == l2.

因此,要更直接地回答您的问题,您可能需要使用:

So, to answer your question more directly, you may want to use:

[f(x), f(x)**2, f(x)**3]

不是这个

y = f(x)
[y, y**2, y**3]

当您对副作用特别感兴趣时,无论可能是什么.

when you are specifically interested in the side-effects, whatever that might be.

这篇关于PEP572 中的海象运算符示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆