Home > database >  Unable to understand how free variable value is evaluated within nested closure?
Unable to understand how free variable value is evaluated within nested closure?

Time:02-24

I have created a nested closure which looks as below:

def incrementer(n):
    def inner(start):
        current = start
        def inc():
            nonlocal current
            current  = n
            return current
        return inc
    return inner

fn = incrementer(2)

Now, when I print value of co_freevars for fn I get below output:

print(fn.__code__.co_freevars) -> ('n',)

My understanding is that it should be () because there are no free variables directly inside inner.

Why print(fn.__code__.co_freevars) is not printing ()?

CodePudding user response:

Think about what def inc is actually doing: it’s creating a closure object populated with references (cells) to current and n. For (a closure created for) inner to be able to do that, it must have a reference to n itself.

  • Related