string interpolation for python

Yingjie Lan lanyjie at yahoo.com
Mon Apr 2 11:49:26 EDT 2012


> Right, meaning that both have the same issues 
> of performance, need for

> str(), etc. There's absolutely no difference.


OK, performance. Here is a new solution:
 
Suppose we have a new string method
    str.format_join([...])
taking a list of strings and objects,
with even-indexed ones being strings,
odd-indexed ones being objects.
Each even-indexed string *ends* with a formatting
specification for the next object in the list.
Then we can have:
>>> d"sin($x$) = $ sin(x):0.3f $"
get translated to:
>>> ''.format_join(["sin(%s",x,") = %0.3f", sin(x)])
This seems to be at least as good in performance.


> And no benefit. You lose out on syntax highlighting 
> in your editor and gain nothing.

Gain: readability, terseness, hassle-free, and possibly
better performance if done right.

Syntax highlighting: can be done more creatively.
For dynamic strings, string parts are like normal 
strings, but the embedded expressions are like
normal expressions :)

> 
> sprintf("UPDATE tablename SET modified=now()%{,%s=:%[0]s%} WHERE
> key=%d",array_of_field_names,primary_key_value)
> --> "UPDATE tablename SET modified=now(),foo=:foo,bar=:bar,quux=:quux
> WHERE key=1234"
> 
> You're still paying for no complexity you aren't actually using. 
> It's clear and readable.

You are really good at that. Maybe not everybody is as
experience as you, and I suppose the learning curve is 
kind of hard to climb.

> It's powerful only if you use eval to allow full expression syntax.
> Otherwise, what does it have above str.format()?


Those expressions are embedded, you don't need eval()
to have the result though. Are we on the same page?

> You may well be able to get past the compatibility issues. I'm not yet
> convinced that the new syntax is worth it, but it may be possible.
> 
> Here's a recommendation: Write a parser for your notation that turns
> it into executable Python code (that is, executable in Python 3.3
> without any d"..." support). 

You mean a translator?

The syntax is essential for compatibility.
We must distinguish dynamic strings from common strings.
They will live peacefully together. 
(escaping the '$' in normal strings breaks compatibility, 
and the consequence of forgetting to escape could be
disastrous, so definitely not an option). 

May be d" is too tiny, $"..." is easier to pick out.



Cheers,
Yingjie




More information about the Python-list mailing list