[Python-Dev] variable name resolution in exec is incorrect

Scott Dial scott+python-dev at scottdial.com
Thu May 27 15:09:55 CEST 2010


On 5/27/2010 7:14 AM, Colin H wrote:
> def define_stuff(user_code):
>   context = {...}
>   stuff = {}
>   stuff.update(context)
> 
>   exec(user_code, stuff)
> 
>   return_stuff = {}
>   return_stuff.update(stuff)
> 
>   del return_stuff['__builtins__']
>   for key in context:
>     if key in return_stuff and return_stuff[key] == context[key]:
>       del return_stuff[key]
> 
>   return return_stuff

I'm not sure your application, but I suspect you would benefit from
using an identity check instead of an __eq__ check. The equality check
may be expensive (e.g., a large dictionary), and I don't think it
actually is checking what you want -- if the user_code generates an
__eq__-similar dictionary, wouldn't you still want that? The only reason
I can see to use __eq__ is if you are trying to detect user_code
modifying an object passed in, which is something that wouldn't be
addressed by your original complaint about exec (as in, modifying a
global data structure).

Instead of:
>     if key in return_stuff and return_stuff[key] == context[key]:

Use:
>     if key in return_stuff and return_stuff[key] is context[key]:

-- 
Scott Dial
scott at scottdial.com
scodial at cs.indiana.edu


More information about the Python-Dev mailing list