Whatever happened to String Interpolation?
Fernando Pérez
fperez528 at yahoo.com
Fri Nov 30 14:35:19 EST 2001
Kragen Sitaker wrote:
> Skip Montanaro <skip at pobox.com> writes:
>> (or something else similar) which isn't all that readable either.
>> You just
>> happen to want to embed literal %-signs in your strings. Please
>> correct me if I'm wrong, but changing the character that introduces
>> a value to be
>> interpolated just moves the problem around a bit. I don't think it
>> solves anything.
>
> Ping's PEP has some advantages over %-syntax; in the common case of
> interpolating a variable, you need only type $var, rather than
> %(var)s, and in the less-common case of wanting to interpolate an
> expression evaluated in the current namespace, you can do that too,
> still with one less noise character than the % syntax allows. (I
> have a module that lets you evaluate arbitrary expressions with the
> % syntax, and I've heard other people have written them too.)
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.
So again, I don't really care about embedding explicit %'s in strange
strings. That's such a rare case that I don't mind strange solutions
for it. What I want is a clear, obvious syntax for a problem that
*does* come up constantly. I hope this clarifies what I have in mind.
Cheers,
f
More information about the Python-list
mailing list