5

Let's say I have

def foo(n):
    print("foo",n)

def bar(n):
    print("bar",n)

print("Hello",foo(1),bar(1))

I would expect the output to be:

Hello
foo 1 None
bar 1 None

But instead I get something which surprised me:

foo 1
bar 1
Hello None None

Why does Python call the functions first before printing the "Hello"? It seems like it would make more sense to print "Hello", then call foo(1), have it print its output, and then print "None" as it's return type. Then call bar(1) and print that output, and print "None" as it's return type. Is there a reason Python (or maybe other languages) call the functions in this way instead of executing each argument in the order they appear?

Edit: Now, my followup question is what's happening internally with Python somehow temporarily storing return values of each argument if it's evaluating the expressions left to right? For example, now I understand it will evaluate each expression left to right, but the final line says Hello None None, so is Python somehow remembering from the execution of each function that the second argument and third arguments have a return value of None? For example, when evaluating foo(), it will print foo 1 and then hit no return statement, so is it storing in memory that foo didn't return a value?

9
  • 2
    The arguments are always first evaluated left to right... Commented Aug 6, 2017 at 22:50
  • I've pruned the dupe target list a bit. Most of the targets were talking about order of argument evaluation relative to other arguments; only one of them discussed order of argument evaluation relative to the execution of the function the arguments are passed to, which is what this question is about. Commented Aug 6, 2017 at 23:04
  • @user2357112 Thank you. I edited my question because there's still another part of it I'm not quite sure I understand how it works. Commented Aug 6, 2017 at 23:05
  • 1
    Also, a function returning no values actually returns None by default. Commented Aug 6, 2017 at 23:09
  • 1
    @rb612 Yes, like I said, the intermediate values are computed and stored in temporary variables (this is an implementation detail) and then passed. Commented Aug 6, 2017 at 23:11

4 Answers 4

3

Quoting from the documentation:

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

Bold emphasis mine. So, all expressions are first evaluated and then passed to print.

Observe the byte code for the print call:

  1           0 LOAD_NAME                0 (print)
              3 LOAD_CONST               0 ('Hello')
              6 LOAD_NAME                1 (foo)
              9 LOAD_CONST               1 (1)
             12 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             15 LOAD_NAME                2 (bar)
             18 LOAD_CONST               1 (1)
             21 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             24 CALL_FUNCTION            3 (3 positional, 0 keyword pair)
             27 RETURN_VALUE

foo (LINE 12) and bar (LINE 21) are first called, followed by print (LINE 24 - 3 positional args).

As to the question of where these intermediate computed values are stored, that would be the call stack. print accesses the return values simply by poping them off of the stack. - Christian Dean

Sign up to request clarification or add additional context in comments.

8 Comments

This is great! Thank you! Just curious, is there a part in the byte code that is showing that Python is storing the return value of both foo and bar?
@rb612 Ah. Good question. The byte code does not show this most likely since it is an implementation detail. You can see it is passed (3 positional, 0 keyword pair) so you know it has to be stored somewhere.
@cᴏʟᴅsᴘᴇᴇᴅ "so you know it has to be stored somewhere." - Yes. Specifically it is stored in Python's call stack. In the example given, print access the return values simply by poping them off of the stack.
@cᴏʟᴅsᴘᴇᴇᴅ Have at it :-)
@randomir Sure. I appreciate you looking out for the community.
|
3

As is specified in the documentation:

Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

This thus means that if you write:

print("Hello",foo(1),bar(1))

It is equivalent to:

arg1 = "Hello"
arg2 = foo(1)
arg3 = bar(1)
print(arg1,arg2,arg3)

So the arguments are evaluated before the function call.

This also happens when we for instance have a tree:

def foo(*x):
    print(x)
    return x

print(foo(foo('a'),foo('b')),foo(foo('c'),foo('d')))

This prints as:

>>> print(foo(foo('a'),foo('b')),foo(foo('c'),foo('d')))
('a',)
('b',)
(('a',), ('b',))
('c',)
('d',)
(('c',), ('d',))
(('a',), ('b',)) (('c',), ('d',))

Since Python thus evaluates arguments left-to-right. It will first evaluate foo(foo('a'),foo('b')), but in order to evaluate foo(foo('a'),foo('b')), it first needs to evaluate foo('a'), followed by foo('b'). Then it can all foo(foo('a'),foo('b')) with the results of the previous calls.

Then it wants to evaluate the second argument foo(foo('c'),foo('d')). But in order to do this, it thus first evaluates foo('c') and foo('d'). Next it can evaluate foo(foo('c'),foo('d')), and then finally it can evaluate the final expression: print(foo(foo('a'),foo('b')),foo(foo('c'),foo('d'))).

So the evaluation is equivalent to:

arg11 = foo('a')
arg12 = foo('b')
arg1 = foo(arg11,arg12)
arg21 = foo('c')
arg22 = foo('d')
arg2 = foo(arg11,arg12)
print(arg1,arg2)

Comments

2

The enclosing function is not called until all of its arguments have been evaluated. This is consistent with the basic rules of mathematics that state that operations within parentheses are performed before those outside. As such print() will always happen after both foo() and bar().

3 Comments

This makes sense, so is the return value of None just stored somewhere for foo and bar until the print statement is called? It seems like it would make sense for None to appear immediately following the execution of foo and bar respectively.
Operations within parentheses aren't always performed before those outside, in math or in Python. While it's common to teach precedence as "order of operations" in early math classes, even in math, it's just an argument grouping convention.
@rb612: Nothing can "appear", since print() hasn't even been invoked yet.
1

The answer is simple: In python the arguments of a function like print are always first evaluated left to right.

Take a look at this stackoverflow question: In which order is an if statement evaluated in Python

And None is just the return value of the function. It executes the function first and then print its return value

1 Comment

Thank you, this is very helpful. I edited my question with a followup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.