[Python-Dev] eval() accepts compiled 'exec' statements
tjreedy at udel.edu
Sat Aug 16 22:45:32 CEST 2008
Patrick Maupin wrote:
> This may or may not be relevant to 2.6 or 3.0 (because I don't have
> those handy at the moment), but on 2.5 and earlier:
> Python 2.5.2 (r252:60911, May 7 2008, 15:19:09)
> [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> print eval(compile('print "It works"\n', '', 'exec'))
> It works
print( eval(compile('print( "It works")\n', '', 'exec')))
does the same thing. So does
print( exec(compile('print( "It works")\n', '', 'exec')))
and I presume the exec statement would in 2.x.
> Personally, I'm absolutely fine with this (because I have a use case,
The only possible use I can think of would be is you are eval-ing
mixed-kind code objects:
def eval_and_go(cobj): # cobj = code object of whatever kind
x = eval(cobj)
if x is not None: # was not side-effect only
> but eval() does work differently for compiled vs
> non-compiled objects, and this behavior doesn't match what the doc at
> http://docs.python.org/lib/built-in-funcs.html says, namely "This
> function can also be used to execute arbitrary code objects (such as
> those created by compile()). In this case pass a code object instead
> of a string. The code object must have been compiled passing 'eval' as
> the kind argument."
> That doc statement is, itself, contradictory. How can it be an
> "arbitrary code object" if it must have been compiled using 'eval'?
> Perhaps all that is meant is "In order to return a result other than
> None to eval's caller, the code object must have been compiled
> passing 'eval' as the kind argument."
> So, either the code or the doc should be fixed. I would vote +1 for
> fixing the doc to match the code, but then I'm the sort of
> dysfunctional programmer who sometimes has a use-case for expressions
> with side-effects.
I filed a condensed version of this report, with my suggested added text, as
More information about the Python-Dev