[Q] How to exec code object with local variables specified?
Terry Reedy
tjreedy at udel.edu
Thu Sep 20 12:18:00 EDT 2012
On 9/20/2012 7:27 AM, Makoto Kuwata wrote:
> Is it possible to run code object with local variables specified?
In the way you mean that, no.
> I'm trying the following code but not work:
>
> def fn():
> x = 1
> y = 2
> localvars = {'x': 0}
> exec(fn.func_code, globals(), localvars)
The globals and locals you pass to exec are the globals and locals for
the context in which the code object runs. They have nothing to do with
the code objects local namespace.
Running exec with separate globals and locals is like running the code
within a class definition context. If you ran
def fn(): x = 1
class dummy:
fn()
dummy.x would not be defined and I presume you would not expect it to.
--
Terry Jan Reedy
More information about the Python-list
mailing list