[Tutor] What are *appropriate* uses for exec() and eval() ?

Cameron Simpson cs at zip.com.au
Tue Feb 17 04:20:38 CET 2015


On 16Feb2015 19:10, Devin Jeanpierre <jeanpierreda at gmail.com> wrote:
>On Mon, Feb 16, 2015 at 6:15 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> Here is a fork of that recipe. It uses an inner class for the new
>> namedtuple class. The only thing which needs exec is the __new__ method.
>>
>> http://code.activestate.com/recipes/578918-yet-another-namedtuple/
>>
>> This demonstrates a powerful truth about Python: *most of the time* you
>> don't need to use exec or eval because the standard language features
>> are powerful enough to solve the problem for you. Using a dynamically
>> created inner class is *almost* enough to solve this problem, only the
>> __new__ method defeats it. If our requirements where just a little less
>> demanding, we could avoid exec completely.
>
>No, exec is not necessary at all. If they had to the author could have
>reimplemented the argument assignment logic by hand. [... example...]

I see your counter counter example and raise you another counter.

One might use exec() to use code that is valid in one python version but not 
another, when you need your program to run in both i.e. to get code that is 
syntacticly invalid in one version, but to use it (conditionally) in another 
version.

I only have one use case for this presently: I have a use of exec() in my 
cs.py3 python2/3 compatability module:

  def raise3(exc_type, exc_value, exc_traceback):
    if sys.hexversion >= 0x03000000:
      raise exc_type(exc_value).with_traceback(exc_traceback)
    else:
      # subterfuge to let this pass a python3 parser; ugly
      exec('raise exc_type, exc_value, exc_traceback')

I'm using exec() here because a Python 3 interpreter will reject the 3 argument 
form of raise. Elsewhere in my code I just call cs.py3.raise3() with the 
requisite arguments. Note that the string passed to exec() is hardwired, not 
obtained from elsewhere in any form.

Like all sane people, I consider using exec() a code smell: if you're using it 
you should consider heavily alternatives to it.

Cheers,
Cameron Simpson <cs at zip.com.au>

I think... Therefore I ride.  I ride... Therefore I am.
        - Mark Pope <erectus at yarrow.wt.uwa.edu.au>


More information about the Tutor mailing list