Get locals () in the order of variable declaration - python

For example,

a = 1

b = 2 

c = 3

      

When called, locals()

I get

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

      

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

+3


source to share


2 answers


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

The __code__

object attribute .co_varnames

stores variables in a specific order. This extended example is instructive in that it shows how arguments are passed to functions as well as internal 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 the differences 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

      

+4


source


In light of the fact that locals () does not restore functional 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)])

      

0


source







All Articles