Questions about `locals` builtin

Kirill Balunov kirillbalunov at gmail.com
Mon Feb 26 13:55:35 EST 2018


Hi,

I am a little bit confused with `locals` builtin in these moments:

1. The documentation says that _free varaibles_ are returned, which seems
incorrect description. In my mind the term free variable refers to
variables used in a function that are not local variables nor parameters of
that function.

    In docs: "Update and return a dictionary representing the current local
symbol table. Free variables are returned by `locals()` when it is called
in function blocks, but not in class blocks."

>>> def func():

    b = 12

    print(locals(), ' : ', id(locals))

    c = 13

    print(locals(), ' : ', id(locals))


>>> print("Free variables: ", func.__code__.co_names)
>>> print("Local variables: ", func.__code__.co_varnames)

Free variables: ('print', 'locals', 'id')
Local variables: ('b', 'c')


2. The documentation has a note that "The contents of this dictionary
should not be modified". Which implies that it is a read only mapping. So
the question why it is `dict` instead of `types.MappingProxyType`?

3. There is one more moment: local variables had been determined when
function was compiled. But `locals` returns _some_ current runtime copy. I
find this also confusing:


>>> def func1():

    loc = locals()

    b = 12

    return loc


>>> def func2():

    b = 12

    loc = locals()

    return loc


>>> func1()
{ }
>>> func2()
{'b': 12}


With kind regards,
-gdg



More information about the Python-list mailing list