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

Devin Jeanpierre jeanpierreda at gmail.com
Wed Feb 18 06:22:23 CET 2015


On Tue, Feb 17, 2015 at 7:31 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Mon, Feb 16, 2015 at 07:10:21PM -0800, Devin Jeanpierre 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.
>
> I'm not sure that I said that exec was "necessary" anywhere,

You said that most of the time you don't "need" to use it. You then
explained how you narrowly had to use exec in this case, and could
have avoided it if the restrictions were relaxed.

That sure sounds like you were saying it was necessary. Maybe you
meant to say something else?

> but since
> you mention it, how about the two earlier examples I gave, timeit and
> doctest? Especially doctest. How would you implement doctests without
> exec?

I already covered this in my response to Cameron: I only meant that in
this particular case exec is not needed.

>> If they had to the author could have
>> reimplemented the argument assignment logic by hand. They chose not to
>> because it is "too hard". (And it is.)  Fortunately, they don't have
>> to go that far:
>>
>> signature = inspect.Signature([
>>     inspect.Parameter(field_name, inspect.Parameter.POSITIONAL_OR_KEYWORD)
>>     for field_name in field_names])
>
> Hmmm. Well, namedtuple was added to Python in version 2.6.
[snip]
> So much for that idea.

What? Why should what was impossible in the past stop you from doing
what is possible now?

-- Devin


More information about the Tutor mailing list