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

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!).

Leave a Comment