Search code examples
pythonargumentsoperator-precedence

Is it safe to rely on Python function arguments evaluation order?


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.


Solution

  • 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