Is it possible to get the erroneous variable when getting a NameError exception?

Dotan Barak dotanba at gmail.com
Sat Dec 26 10:12:35 EST 2009


> A simple expression is enough to write to files, for example.
>
> Try this expression in Python 3.0:
>
>    [x for x in ().__class__.__base__.__subclasses__() if x.__name__ == 
> '_FileIO'][0]('hello.txt', 'w').write('Hello, World!')
>
>
> To explain, "().__class__.__base__.__subclasses__()" gives you a list 
> of all object-derived classes, i.e., of *all* classes that exist in 
> the surrounding program. If you can find just one class that allows 
> you to do something subtle or dangerous, you're done.
>
> See also:
> - "Controlling Access to Resources Within The Python Interpreter" 
> (http://people.cs.ubc.ca/~drifty/papers/python_security.pdf)
> - http://evoque.gizmojo.org/usage/restricted/
>
>
>
> To write your own restricted expression parser, the standard module 
> "ast" is quite useful. For example, ast.parse("my_number < 10") gives 
> you a syntax tree similar to this:
>
>   ast.Expr(ast.Compare(ops=[ast.Lt], left=ast.Name(id="my_number"), 
> comparators=[ast.Num(n=10)]))
>
> From there, you can implement your own logic to traverse the tree, 
> which gives you very fine-grained control over the kinds of 
> expressions to allow, where to look up variable names, how to react to 
> errors, etc.
>
>
> Kind Regards,
> M.F.
Hi all.

First of all, thank you very much for your response.

The answers I got made me think if I'm trying to solve a problem because 
of the way I'm doing things;
I tried to evaluate a string that a user supplied to me and try to get 
the various python exceptions to
make the user understand what was his error.

My original idea was to get the bad symbol, and print the user a more 
"friendly" error message.

I think that the direction that Michael showed me is better, and It is a 
better solution
(maybe, first I need to traverse the tree, give the right error 
messages  and only then execute the eval).

Thanks!!!
Dotan




More information about the Python-list mailing list