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

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

问题描述

可以安全地假设函数参数是在Python中从左到右求值的吗?

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.

推荐答案

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

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天全站免登陆