Search code examples
pythonparameter-passingoptional-arguments

Why doesn't using nonlocal scope variable as default value for parameter work?


Code would explain this much better :)

def a():
    x=0
    def b(z=x):
        print("X: %d, Z: %d" % (x,z,))
    x=5
    b()

Result:

X: 5, Z: 0

What's going on here?

(Ok, now I've figured it out)


Solution

  • Ok, the answer from the Python docs is:

    Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.

    Fair enough.