python - How to capture the current namespace inside nested functions? -
suppose 1 had 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 inner
dictionary obtained merging dictionaries returned globals()
, locals()
, shown. in general1, returned value not contain entries foo
, bar
, baz
, , frobozz
, though these variables visible within inner
, , therefore, arguably belong in inner
's namespace.
one way facilitate capturing of inner
's namespace 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 better way capture inner
's namespace sort of kluge?
1 unless, is, variables having names happen present in current global namespace.
this isn't dynamic, , it's not best way, could access variables inside inner
add them "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 store outer
function's locals variable, , use variable inside inner
's 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)
Comments
Post a Comment