Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #29556

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

From Terry Reedy <tjreedy@udel.edu>
Subject Re: [Q] How to exec code object with local variables specified?
Date 2012-09-20 12:18 -0400
References <CAFTm5Ru=E8Zii4k54fc4ii43wKPSwTq=iT4iRQCWy=46YiEZZw@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.962.1348157899.27098.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: [Q] How to exec code object with local variables specified? Terry Reedy <tjreedy@udel.edu> - 2012-09-20 12:18 -0400

csiph-web