pythonpython-3.xscoping

Function assigned to a variable?


def f(x):
    def g():
        x = 'abc'
        print ('x =', x)
    def h():
        z = x
        print ('z =', z)
    x = x + 1
    print ('x =', x)
    h()
    g()
    print ('x =', x)
    return g
x = 3
z = f(x)
z()

return value of f() is assigned to variable z when this happens it invokes function f() I understand so far but how does z() directly returns the value returned by f ? Could you explain this briefly ?


Solution

  • You assign the returnvalue of the call of f() to z. You do not assign f to z.

    So calling z() will only execute the returned inner g function - not the whole f.

    On z = f() you get the printout of f and then g as function returned. On consecutive calls to z() you execute the inner g function directly.