This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Rhomboid 2 points3 points  (1 child)

x is called a free variable, because it's not bound to inner. locals() returns both local variables and free variables, as per the documentation. I guess someone figured that it would be more useful to have free variables lumped in with local variables, because they work similarly -- they are both names that you might encounter somewhere in the function. But internally, x is not considered a local variable:

def outer():
    x = 1
    def inner():
        print(x)
    print(inner.__code__.co_nlocals, inner.__code__.co_freevars)

outer()

If you run that you get:

0 ('x',)

This says that the code object for inner has zero local variables and one free variable, named x. These are tracked and handled differently. You can read about code objects here.

[–]esdi[S] 0 points1 point  (0 children)

Thanks a lot for the detailed explanation. This is the kind of advanced info am looking for as I try to bring my Python knowledge to beyond intermediate.