How to capture the current namespace inside nested functions?

Suppose one of them had the following:

def outer(foo, bar, baz): frobozz = foo + bar + baz def inner(x, y, z): return dict(globals().items() + locals().items()) return inner(7, 8, 9) 

The value returned by inner is the dictionary obtained by merging the dictionaries returned by globals() and locals() , as shown. In general case 1, this return value will not contain entries for foo , bar , baz and frobozz , although these variables are visible inside inner , and therefore, possibly belong to the inner namespace.

One way to make it easier to capture the inner namespace is to use the following kluge:

 def outer(foo, bar, baz): frobozz = foo + bar + baz def inner(x, y, z, _kluge=locals().items()): return dict(globals().items() + _kluge + locals().items()) return inner(7, 8, 9) 

Is there a better way to capture the inner namespace than this kluge type?


1 If variables with these names are not present in the current global namespace.

+4
source share
1 answer

This is not dynamic, and most likely this is not the best way, but you can just access the variables inside inner to add them to your "namespace":

 def outer(foo, bar, baz): frobozz = foo + bar + baz def inner(x, y, z): foo, bar, baz, frobozz return dict(globals().items() + locals().items()) return inner(7, 8, 9) 

You can also save the locals outer in a variable and use the variable inside the inner return value:

 def outer(foo, bar, baz): frobozz = foo + bar + baz outer_locals = locals() def inner(x, y, z): return dict(outer_locals.items() + globals().items() + locals().items()) return inner(7, 8, 9) 
+1
source

All Articles