[Q] How to exec code object with local variables specified?

Makoto Kuwata kwa at kuwata-lab.com
Thu Sep 20 07:27:37 EDT 2012


Hi,

Is it possible to run code object with local variables specified?
I'm trying the following code but not work:

    def fn():
       x = 1
       y = 2
    localvars = {'x': 0}
    exec(fn.func_code, globals(), localvars)
    print(localvars)
    ## what I expected is: {'x': 1, 'y': 2}
    ## but actual is:      {'x': 0}

Python: 2.7.3
OS: MacOS X

--
regards,
makoto kuwata



More information about the Python-list mailing list