1

I've stumbled on a piece of code which looks like this:

x = 12
def f1(a,b=x):
    print(a,b)

x = 15
f1(4)

And in mind, I surely thought the answer is 4 15 since the call of the f1 is after I assign x to 15, when I ran it I got 4 12.

Why does it not print out 4 15 since x is 15 when I call f1?

EDIT

x = 12
def f1(a,b=x):
    print(x)
    print(b)
    print(a,b)

x = 15
f1(4)

Prints out

15
12
4 12

So the question becomes why b is not being updated with the new value of x?

Jonas Palačionis
  • 4,591
  • 4
  • 22
  • 55
  • 1
    Heh @Gabip, I was just updating my answer to include that link as well. Such link should help clarify the confusion indeed. – Lonami Apr 07 '20 at 11:08
  • instead of expecting the default argument to change based on the state when the function is called, why not just pass in the new value: `f1(4, x)`. This is a far simpler pattern. – Dan Apr 07 '20 at 11:12
  • It's just a random code block I've found on Reddit, I wouldn't use this, just curious. – Jonas Palačionis Apr 07 '20 at 11:15

1 Answers1

2

When you do f1(b=x), the default of b now points to the same reference as x did. That is, both x and b refer to 12 now.

Changing what reference x points to later (15) does not affect what b points to (it's still 12).

See also How do I pass a variable by reference?, and perhaps “Least Astonishment” and the Mutable Default Argument helps too.

Lonami
  • 5,945
  • 2
  • 20
  • 38