5

I am learning Python and came across an example that I don't quite understand. In the official tutorial, the following code is given:

i = 5

def f(arg=i):
    print(arg)

i = 6
f()

Coming from c++, it makes sense intuitively for me that this will print 5. But I'd also like to understand the technical explanation: "The default values are evaluated at the point of function definition in the defining scope." What does the "defining scope" mean here?

Maroun
  • 94,125
  • 30
  • 188
  • 241
uncreative
  • 341
  • 5
  • 11
  • 2
    *"Defining scope"* means the scope in which the function is being defined, i.e. the one containing `i = 5`, where the `def` line is executed. See also: http://stackoverflow.com/q/1132941/3001761 – jonrsharpe Jun 20 '16 at 08:58
  • "Defining scope": in Python you can have a locally scoped function, i.e. a function within a function. The closest you get to that in C++ is a lambda, which are newish in C++ (Python has lambdas as well). – cdarke Jun 20 '16 at 09:02
  • Short answer: default values are stored as tuple in `f.func_defaults`, its value is `(5,)` in your code. – gdlmx Jun 20 '16 at 09:11

1 Answers1

1
1. i = 5
2. 
3. def f(arg=i):
4.     print(arg)
5. 
6. i = 6
7. f()

At #1, i = 5 is evaluated and the variable and its value is added to the scope.

At line 3, the function declaration is evaluated. At this point all the default arguments are also evaluated. i holds the value 5, so arg's default value is 5 (and not the symbolic i).

After i changes value on line 6, arg is already 5 so it doesn't change.

André Laszlo
  • 15,169
  • 3
  • 63
  • 81