Search code examples
pythonparameter-passingoperator-precedence

How to prove that parameter evaluation is "left to right" in Python?


For example, in JavaScript we could write a program like this:

var a = 1;
testFunction(++a, ++a, a);
function testFunction(x, y, z){
      document.writeln("<br />x = " + x);
      document.writeln("<br />y = " + y);
      document.writeln("<br />z = " + z);
}

and we would get an output:

x = 2
y = 3
z = 3

This implies that parameters are truly evaluated from left to right in JavaScript. In C we would get output

x = 3
y = 3
z = 3

I was wondering if we could do the same in Python or is it impossible since it's a pass by value reference language?

I've made a simple program but I don't think that proves anything:

x = 2
def f(x, y, z):
    print(x, y, z)

f(x*2, x*2, x**2)
print(x)
4 4 4
2

Python won't let me do any new assignment within the function parameter when I call it (for example f(x=4, x, x) or something like this).


Solution

  • >>> def f(x, y): pass
    ...
    >>> f(print(1), print(2))
    1
    2