eval or execute, is this the (most) correct way ?

"Martin v. Löwis" martin at v.loewis.de
Mon Aug 11 18:20:52 EDT 2008


>> You should be using compile with the "single" start symbol, and then
>> use eval on the resulting code option.
>>
>>   
> thanks Martin,
> but when I read the doc (of one of the many) "compile" functions,
> I see 2 problems:
> - I still have to provide "kind" as exec or eval

No, you can also use "single".

> - I can not specify the global and local namespace (which is essential
> for me)

You do so not in compile, but in eval.

> That's good to hear,
> as I already didn't realize it could also be used as a statement ;-)

It *is* a statement, and always was. A "statement" is a fragment of
code that just gets executed, and doesn't produce a value (unlike
an expression, which does produce a value). So you can't write

  x = exec "1+1"

or

  foo(exec)

whereas you *can* write

  x = eval("1+1")

and

  foo(eval)

Likewise, you cannot write in Python 2.x, but can write in 3.x

   x = print("Hello")

and

   foo(print)

Things like "for", "while", "return", and assignments are statements,
things like "+", "**", lambda, function calls are expressions. print
and exec are statements in 2.x, and functions (thus, expressions)
in 3.x.

Regards,
Martin



More information about the Python-list mailing list