safe eval of moderately simple math expressions

Joel Hedlund yohell at ifm.liu.se
Sat Apr 11 11:03:16 CEST 2009


Peter Otten wrote:
> But what you're planning to do seems more like
> 
>>>> def is_it_safe(source):
> ...     return "_" not in source
> ...
>>>> source = "getattr(42, '\\x5f\\x5fclass\\x5f\\x5f')"
>>>> if is_it_safe(source):
> ...     print eval(source)
> ...
> <type 'int'>

Bah. You are completely right of course.

Just as a thought experiment, would this do the trick?

def is_it_safe(source):
     return "_" not in source and r'\' not in source

I'm not asking because I'm hellbent on having eval in my app, but 
because it's always useful to see what hazards you don't know about.

/Joel



More information about the Python-list mailing list