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

Discussion in 'Python' started by Terry Reedy, Sep 20, 2012.

  1. Terry Reedy

    Terry Reedy Guest

    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
     
    Terry Reedy, Sep 20, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Hal Vaughan
    Replies:
    11
    Views:
    1,198
    Gordon Beaton
    May 22, 2006
  2. Makoto Kuwata
    Replies:
    2
    Views:
    184
    88888 Dihedral
    Sep 21, 2012
  3. Peter Otten
    Replies:
    0
    Views:
    155
    Peter Otten
    Sep 20, 2012
  4. Makoto Kuwata
    Replies:
    0
    Views:
    162
    Makoto Kuwata
    Sep 20, 2012
  5. Peter Otten
    Replies:
    0
    Views:
    165
    Peter Otten
    Sep 21, 2012
Loading...

Share This Page