Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope for default parameter in Python [duplicate]

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?

like image 631
uncreative Avatar asked Nov 09 '22 13:11

uncreative


1 Answers

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.

like image 79
André Laszlo Avatar answered Nov 14 '22 22:11

André Laszlo