Get a dict of all variables currently in scope and their values

python

Solution

Best way to merge two dicts as you're doing (with locals overriding globals) is `dict(globals(), **locals())`.

What the approach of merging globals and locals is missing is (a) builtins (I imagine that's deliberate, i.e. you don't think of builtins as "variables"... but, they COULD be, if you so choose!-), and (b) if you're in a nested function, any variables that are local to enclosing functions (no really good way to get a dict with all of those, plus -- only those explicitly accessed in the nested function, i.e. "free variables" thereof, survive as cells in a closure, anyway).

I imagine these issues are no big deal for your intended use, but you did mention "corner cases";-). If you need to cover them, there are ways to get the built-ins (that's easy) and (not so easy) all the cells (variables from enclosing functions that you explicitly mention in the nested function -- `thefunction.func_code.co_freevars` to get the names, `thefunction.func_closure` to get the cells, `cell_contents` on each cell to get its value). (But, remember, those will only be variables from enclosing functions that are explicitly accessed in your nested function's code!).

Problem

Consider this snippet: ``` globalVar = 25 def myfunc(paramVar): localVar = 30 print "Vars: {globalVar}, {paramVar}, {localVar}!".format(**VARS_IN_SCOPE) myfunc(123) ``` Where `VARS_IN_SCOPE` is the dict I'm after that would contain `globalVar`, `paramVar` and `localVar`, among other things. I'd like to basically be able to reference all the variables that are currently in scope inside the string. Hence the expected output would be: `Vars: 25, 123, 30` I can achieve this by passing `**dict(globals().items() + locals().items())` to `format()`. Is this always correct or are there some corner cases that this expression would handle incorrectly? Rewritten to clarify the question.

Original source