string interpolation for python

Yingjie Lan lanyjie at yahoo.com
Mon Apr 2 03:24:21 EDT 2012


Hi Adrian, see my comments below.
>________________________________
> From: Adrian Hunt <cyborgv2 at hotmail.com>
...
>It could break old code... okay you may say you should’nt allow 
>certain characters but if they're printable and used in a controlled
>environment those characters can dramatically increase the security
>of a username and password.


What you said makes lots of sense to me. 
if strings are interpolated *automatically*.

But it won't and shouldn't.

They are called "Dynamic strings".
Dynamic strings can achieve formatting, 
but the mechanism under the hood differ
from common strings dramatically.

Many here didn't realize that this is not
another formatting proposal, it is a new
kind of *expression*. 

To have it in Python, we will need 
a new kind of syntax to distinguish it
from other strings, such as raw strings 
and the like. A raw string looks like:

>>> r'my\\ raw str'
'my\\\\ raw str'

A dynamic string may look like this:

>>> name = "Peter" #common string
>>> d"Thank you, $name$!" #dynamic string!
'Thank you, Peter!'


The following example would make it feel 
a lot more safe (suppose a = raw_input()):

>>> a = 'd"Are you $name$?"'
>>> print(a)
'd"Are you $name$?"'

>>> eval('d"Are you $name$?"')

'Are you Peter?'
>>> d"It contains $len(_.split())$ words!"
'It contains 3 words!'

An interesting question might be:
what if a dynamic string is referring
to another dynamic string, which
in turn refers back to the former?

The answer is: no variable can hold
a dynamic string itself, only its result,
which can only be a common string.

However, a infinite recursion may 
occur if the eval function is used inside:

>>> a = 'd"$eval(a)$"'
>>> eval(a)

This is just to show a dynamic string
is really an expression in disguise.
Like evaluating any expression containing
function calls, there is risk of getting into
infinite recursion.

Cheers, 

Yingjie



More information about the Python-list mailing list