5

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?

vivify
  • 53
  • 2

2 Answers2

5

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
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
0

In light of the fact that locals() doesn't retrieve function parameters in order, I created a utility function for debugging purposes.

import inspect
import logging
import traceback

def get_function_name():
    return traceback.extract_stack(None, 2)[0][2]

def get_function_parameters_and_values():
    frame = inspect.currentframe().f_back
    args, _, _, values = inspect.getargvalues(frame)
    return ([(i, values[i]) for i in args])

def my_func(a, b, c=None):
    logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')')
    pass

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
    '%(asctime)s [%(levelname)s] -> %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

my_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -> Running my_func([('a', 1), ('b', 3), ('c', None)])
Jim G.
  • 15,141
  • 22
  • 103
  • 166
  • 1
    Worth noting that this doesnt answer the question of how to get local variables in order. This answer instead gets the parameters in order – RyanS Dec 13 '17 at 19:26
  • Since 3.7 (released in 2018), dictionaries are now ordered. Will locals() return function parameters in order for Python >= 3.7? – michen00 Aug 31 '22 at 05:48