Why can't I change the default value of a function after it was defined?

def f(arg=i) says "make me a function f where the default value for arg is whatever i is right now". At the time of defining the function, i=5.


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

The i is evaluated at the time of definition, so the code above has the same meaning as the code below:

def f(arg=5)
    print(arg)

This means that, when the function is called without arguments, arg will have the value 5, no matter what the value of i is now.

In order to get what you want, just do the following:

def f(arg)
    print(arg)

i = 6
f(i)

Because the function takes its default value on the first declaration of 'i'.

Change to i=6 on the first line if you want you code to print 6.

Hope I helped !

Tags:

Python