Note: this question assumes Python 2.7.3.
I am looking for a sensible approach to dynamically changing the local function namespace, preferably in a way that adds the least mess to the body function.
What I mean will look something like this:
import os
from namespace_updater import update_locals
def somefunc(x, y, z):
if os.environ.get('FROBNICATE'):
from frobnitz import frobnicate
update_locals(frobnicate(locals()))
Thank!
PS: Below are the approaches that do not work.
The most naive approach to this is something like:
locals().update(new_locals(locals())
... but the documentation forlocals() explicitly forbids relying on such a voodoo to change local variables, so please do not send this as an answer (unless you can make a great case to ignore the documentation warning).
Further on the naive scale there is something like
for k, v in new_locals(locals()).items():
exec ('%s = v' % k)
AFAICT, " " (.. ), . , exec ('%s = v' % k) .
" ", ", - exec ('%s = v' % k) ". ? , script . : (1) , ; (2) # 18; (3) # 15 18 (.. ). (2) (3) script. 50- (1). , - exec ('%s = v' % k). , script ( python 2.7), , , , , , exec ('%s = v' % k) .
x = 'global x'
y = 'global y'
def main():
x = 'local x'
y = 'local y'
run(locals())
print 'OK'
return 0
def run(namespace):
global y
print locals().keys()
for k, v in namespace.items():
print '%s <- %r' % (k, v)
exec ('%s = v' % k)
print locals().keys()
x = x
print x
print y
exit(main())