依赖 Python 函数参数评估顺序是否安全? [英] Is it safe to rely on Python function arguments evaluation order?

查看:25
本文介绍了依赖 Python 函数参数评估顺序是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设函数参数在 Python 中从左到右求值是否安全?

Reference 指出它是这样发生的,但也许有一些方法可以改变这个顺序,这可能会破坏我的代码.

我想做的是为函数调用添加时间戳:

l = []l.append(f(), time.time())

我知道我可以按顺序评估参数:

l = []res = f()t = time.time()l.append(res, t)

但它看起来不太优雅,所以如果我可以依靠它,我更喜欢第一种方式.

解决方案

是的,Python 总是从左到右计算函数参数.

据我所知,这适用于任何逗号分隔的列表:

<预><代码>>>>从 __future__ 导入 print_function>>>def f(x, y):通过...>>>f(打印(1),打印(2))12>>>[打印(1),打印(2)]12[无,无]>>>{1:打印(1),2:打印(2)}12{1:无,2:无}>>>def f(x=print(1), y=print(2)):通过...12

Is it safe to assume that function arguments are evaluated from left to right in Python?

Reference states that it happens that way but perhaps there is some way to change this order which may break my code.

What I want to do is to add time stamp for function call:

l = []
l.append(f(), time.time())

I understand that I can evaluate the arguments sequentially:

l = []
res = f()
t = time.time()
l.append(res, t)

But it looks less elegant so I'd prefer the first way if I can rely on it.

解决方案

Yes, Python always evaluates function arguments from left to right.

This goes for any comma seperated list as far as I know:

>>> from __future__ import print_function
>>> def f(x, y): pass
...
>>> f(print(1), print(2))
1
2
>>> [print(1), print(2)]
1
2
[None, None]
>>> {1:print(1), 2:print(2)}
1
2
{1: None, 2: None}
>>> def f(x=print(1), y=print(2)): pass
...
1
2

这篇关于依赖 Python 函数参数评估顺序是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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