dict to boolean expression, how to?

Terry Reedy tjreedy at udel.edu
Fri Aug 1 18:16:54 EDT 2014


On 8/1/2014 11:02 AM, Steven D'Aprano wrote:
> On Fri, 01 Aug 2014 09:32:36 -0400, Roy Smith wrote:
>
>> In article <53db95e6$0$29986$c3e8da3$5496439d at news.astraweb.com>,
>>   Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
>>
>>> eval is almost never the right solution to any problem, and in the very
>>> few exceptions, it needs careful handling by an expert to ensure you're
>>> not introducing serious security bugs.
>>
>> Corollary to that rule: All the people who are smart enough to actually
>> understand how to use eval() safety, are also smart enough to know not
>> to use it.

Eval is a specialized version of exec. Everything you do on a computer 
is evaluating and executing code. Here is a highly simplified version of 
a Python interpreter:

user_program = get_user_python_code()
__main__ = make_global_namespace()
exec(user_program, __main__, __main__)

CPython codes an expansion of the above in C. Idle uses an expansion of 
the above to do the same thing.

The threat model is executing code from someone who does not have 
physical access to a machine to just run code and who should not be trusted.

> ... smart enough to know WHEN to use it (which is *rarely*).
>
> That's in production code, of course. There's nothing wrong with using
> eval in the interactive interpreter for quick and dirty exploration. But
> even then, I find that it's usually easier to write a line or two of
> Python code to process something than to try using eval.
>
> There are uses for eval (or exec), even if production code. See
> collections.namedtuple, doctest, and timeit, for example. In the first
> place, namedtuple takes extra care to sanitise the data being used. In
> the case of doctest and timeit, the whole point of them is to run trusted
> code. If you can't trust your own code that you're timing, what can you
> trust?

Exactly. If someone can start Python or Idle on a machine, they can 
start Windows Explorer and Command Prompt. Idle exec's user code because 
emulating the interactive interpreter is part of its purpose. It 
sometimes evals expression within user code in response to user requests.

-- 
Terry Jan Reedy




More information about the Python-list mailing list