Draft PEP: string interpolation with backquotes

Fernando Pérez fperez528 at yahoo.com
Sat Dec 1 13:00:41 EST 2001


John Roth wrote:

> 
> "Oren Tirosh" <oren-py-l at hishome.net> wrote in message
> news:mailman.1007298422.20078.python-list at python.org...
> 
> I don't see what I could do with this that I couldn't do with the
> '%' operator.
> Someone help me out on this?
> 
> John Roth

Here's a copy of an older post of mine. It concerned another pep 
implementing the same idea with $ instead of ``. But the discussion 
is the same:


--------------# begin paste

Exactly my point. I think when I mentioned my need of inserting % in 
strange dynamic strings I inadvertedly set the discussion off-course. 
That was just a side comment, and by no means the meat of my point. 
My important point is that Ping's PEP allows a clear way of saying 

        "x is $x, f(x) is $f(x)"

This to me is readable, unambiguous and very useful. Currently we 
have a few options. Please keep in mind that this is really important 
only when the string and evaluations to handle grows dramatically in 
size and complexity. Think of 50 line strings with 100 complex 
expression evaluations embedded (and yes, things like that can happen 
fairly easily):

1)
"x is %s, f(x) is %s" % (x,f(x))

Comment: this is very fragile and only works for a few %s. Beyond 
that it's asking for trouble. Plus visually parsing it is a pain, as 
you have to go back and forth between the string and the format tuple.

2)
tmp = f(x)
"x is %(x)s, f(x) is %(tmp)s" % locals()

A little better than 1. But requires temporary variables. Again, for 
complex, long cases it gets fragile quickly.

3)
class Eval:
    def __getitem__(self, key):
        return eval(key) 

"x is %(x), f(x) is %(f(x))s" % Eval()

The best option, but the Eval trick, though very clever (when I saw 
it I immediately made a copy of it for future use), is quite deep 
'black magic' for a language that prides itself on clarity.

------------ #end paste

hope this helps,

f



More information about the Python-list mailing list