[Python-porting] Strange behavior of eval() in Python 3.1

Bo Peng ben.bob at gmail.com
Sun Aug 29 18:49:25 CEST 2010


> Surely you can do
>
> namespace = module_dict.copy()
> namespace.update(user_dict)
> eval(..., namespace)

I know, but this would be really slow because a lot of such
evaluations are needed. I think what I will do is to set __builtins__
to user_dict and use eval(expression, user_dict, user_dict) to
evaluate the expressions. Because my expressions rarely involve
variables in module_dict (except for __builtins__), restricting the
expressions to user_dict might be acceptable. If this solution is not
enough, I can still use

try:
    eval(expression, user_dict, user_dict)
except NameError:
    get namespace like what you suggested
    eval(expression, namespace, user_dict)

to handle these rare situations.

Thank you very much for your help,
Bo


More information about the Python-porting mailing list