[Python-Dev] PEP 216 (string interpolation) alternative EvalDict

Paul Prescod paul@prescod.net
Mon, 14 Jan 2002 13:34:41 -0800


Steven Majewski wrote:
> 
>...
> 
>  I'm not sure what you mean by logical indirection here: is that
> a comment on the syntax, or do you object to the idea of not implementing
> substitution by a language syntax change. 

Sorry I wasn't clear. Let's say it's the second hour of our Perl/Python
class.

Here's Perl:

$a = 5;
$b = 6;
print "$a $b";

Lots of yucky extra chars in that code but you can't find much negative
stuff to say about the complexity of the string interpolation!

Here's Python:

a = 5;
b = 6;
print "%(a)s %(b)s" % vars()

Extra indirection: What does % do? What does vars() do? What does the
"s" mean? How does this use of % relate to the traditional meanings of
either percentage or modulus? 

This is one of the two problems I would like PEP 215 to solve. The other
one is to allow simple function calls and array lookups etc. to be done
"inline" to avoid setting up trivial vars or building unnecessary
dictionaries. If I understand your proposal correctly, I could only get
the evaluation behaviour by making the "indirection" problem even
worse...by adding in yet another function call (well, class construtor
call), tentatively called EvalDict.

Another benefit of the PEP 215 model is that something hard-coded in the
syntax is much more amenable to compile time analysis. String
interpolation is actually quite compatible with standard compilation
techniques. You just rip the expressions out of the string, compile them
to byte-code and replace them with pointers ot the evaluated results. As
PEP 215 mentions, this also has advantages for reasoning about security.
If I tell a new programmer to avoid the use of "eval" unless they
consult with me, I'll have to tell them to avoid EvalDict also. My usual
approach is to consider eval and exec to be advanced (and rarely used)
features that I don't even teach new programmers.

I don't know that Jython allows me today to ship a JAR without the
Python parser and evaluator but I could imagine a future version that
would give me that option. Widespread use of EvalDict would render that
option useless.

Re: $ versus %. $ is "the standard" in other languages and shells. % is
the current standard in Python. $ has the advantage that it doesn't have
to work around Python's current C-inspired syntax. So I guess I
reluctantly favor $.

Also, EvalDict should be called evaldict to match the other constructors
in __builtins__.

So while I understand the advantage of non-syntactic solutions, in this
case I am still in favor of the syntax.

 Paul Prescod