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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With