Search code examples
pythonlocals

Retrieve locals() in order of variable declaration - python


For example,

a = 1

b = 2 

c = 3

When call locals(), I get

{ 'a': 1, 'c': 3, 'b': 2, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None }

How can I retrieve local variables from locals() as the order I defined?


Solution

  • You can do this in a function by accessing the code object.

    The __code__ object's .co_varnames attribute stores the variables in the order defined. This expanded example is instructive in that it shows how arguments are passed to the function, as well as internally defined variables:

    def foo(a, b, c=3, d=4, *args, **kwargs):
        e = 5
        f = 6
        g = 7
        for var in foo.__code__.co_varnames:
            print(var, locals()[var])
    

    and now (will look slightly different in Python 2 due to difference between print statement and function.):

    >>> foo(1, 2, *(11, 12, 13), **{'h': 14, 'i': 15, 'j': 16})
    a 1
    b 2
    c 11
    d 12
    args (13,)
    kwargs {'i': 15, 'h': 14, 'j': 16}
    e 5
    f 6
    g 7
    var var