Say I have the following dict:
In [6]: scope
Out[6]: {'bar': <function bar>, 'foo': <function foo>}
And fooand bar:
def foo():
return 5
def bar(x):
return foo() + x
I want to run bar(1), but he will need to find foo(). Is there a way to run bar()in the namespace scopeto find foo()?
I do not know exactly which function scope barwill be needed, so I need a general method for working barin the namespace scope. I have no source code and cannot change any function to accept a dict.
Functions seem to have an attribute __closure__, but it is immutable. There is also an attribute __globals__, but this only indicates globals(). I saw several answers on SO that updated locals(), but I would like to leave it locals()untouched.
eval scope, NameError foo:
In [12]: eval(scope['bar'](1), scope)
NameError Traceback (most recent call last)
<ipython-input-12-f6305634f1da> in <module>()
<string> in bar(x)
NameError: global name 'foo' is not defined
- , ?