exec and locals
Alister
alister.ware at ntlworld.com
Wed Feb 26 09:00:59 EST 2014
On Wed, 26 Feb 2014 13:15:25 +0000, Steven D'Aprano wrote:
> I have to dynamically generate some code inside a function using exec,
> but I'm not sure if it is working by accident or if I can rely on it.
>
> Here is a trivial example:
>
>
> py> def spam():
> ... exec( """x = 23""" )
> ... return x ...
> py> spam()
> 23
>
>
> (My real example is more complex than this.)
>
> According to the documentation of exec, I don't think this should
> actually work, and yet it appears to. The documentation says:
>
> The default locals act as described for function locals() below:
> modifications to the default locals dictionary should not be
> attempted. Pass an explicit locals dictionary if you need to see
> effects of the code on locals after function exec() returns.
>
> http://docs.python.org/3.4/library/functions.html#exec
>
>
> I *think* this means that if I want to guarantee that a local variable x
> is created by exec, I need to do this instead:
>
> py> def eggs():
> ... mylocals = {}
> ... exec( """x = 23""", globals(), mylocals)
> ... x = mylocals['x']
> ... return x ...
> py> eggs()
> 23
>
> The fact that it works in spam() above is perhaps an accident of
> implementation? Yes no maybe?
I have no idea but as exec is generally considered to be a bad idea are
you absolutely sure this is the correct way to achieve your end goal?
perhaps if you detailed your requirement someone may be able to suggest a
safer solution.
--
"Regardless of the legal speed limit, your Buick must be operated at
speeds faster than 85 MPH (140kph)."
-- 1987 Buick Grand National owners manual.
More information about the Python-list
mailing list