local variables in exec

Jeremy Lowery jslowery at hotmail.com
Mon Dec 17 23:46:43 EST 2001


Yes, I saw the silly mistake after I had posted it. Always happens that way.
Well, I agree that it is horrible, but it is the only way I've figured out
how to create function objects from user code running in the app. I
attempted to use new.function for a while but without any success. After
getting the function name from analysis the source with the parser module,
it doesn't seem too bad. Of course, the code I posted was a minimalistic
example, excluding the rexec, bastions, etc.The client code is really stored
in Method objects and compiled on the fly.

Jeremy

"Steve Holden" <sholden at holdenweb.com> wrote in message
news:DGnT7.7648$PA.6490 at atlpnn01.usenetserver.com...
> "Jeremy Lowery" <jslowery at hotmail.com> wrote ...
> > a snipplet would be describe this.
> > >>> x = 100
> > >>> def f():
> > ...  print x
> > ...
> > >>> f()
> > 100
> > >>> lns = {x: '4500'}
> > >>> fc = 'def f(): print x'
> > >>> bc = compile(fc, '', 'exec')
> > >>> exec bc in lns
> > >>> lns['f']()
> > Traceback (most recent call last):
> >   File "<interactive input>", line 1, in ?
> >   File "", line 1, in f
> > NameError: global name 'x' is not defined
> > >>>
> >
> > why doesn't this work?
>
> Because you have stored 4500 in the lns dictionary under the key 100. Use
> the variable name as a string and it works as you expect (but realise you
> are doing things with a high horribleness quotient: while it is
occasionally
> necessary to descend to such depths, one should avoid it where possible).
>
> >>> lns = {"x": "4500"}
> >>> fc = "def f(): print x"
> >>> bc = compile(fc, "", "exec")
> >>> exec bc in lns
> >>> lns['f']()
> 4500
> >>>
>
> regards
>  Steve
> --
> http://www.holdenweb.com/
>
>
>
>
>






More information about the Python-list mailing list