Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python order in which functions in print statement are called?

Tags:

python

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?

like image 816
rb612 Avatar asked Jan 03 '23 15:01

rb612


1 Answers

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

like image 121
cs95 Avatar answered Feb 02 '23 14:02

cs95