string interpolation for python
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Apr 2 04:26:24 EDT 2012
On Mon, 02 Apr 2012 00:39:42 -0700, Yingjie Lan wrote:
>> You can already do essentially that without adding a special-case
>> string
>
>> formatting method to the general methods we already have.
>>
>>>>> balls = 5
>>>>> people = 3
>>>>> 'The {people} people have {balls}
>> balls.'.format(**locals())
>> 'The 3 people have 5 balls.'
>
>
> Clearly dynamic strings are much more powerful, allowing arbitrary
> expressions inside.
And so it may be a security risk, if user-input somehow ends up treated
as a dynamic string.
We already have three ways to evaluate arbitrary expressions:
* Python code
* eval
* exec
Why do we need yet another one?
> It is also more terse and readable, since we need no
> dictionary.
I think you mean terse and unreadable, since we need no dictionary. That
means that variables will be evaluated by magic from... where? Globals?
Local scope? Non-local scope? All of the above?
We already have one way of evaluating implicit variables using implicit
rules, namely regular Python code. Why do we need a second one?
> I would probably rather liken dynamic expressions as a little brother of
> computable documents in Mathematica. It is a new kind of expression,
> rather than formatting -- though it has formatting connections.
Why do we need a new kind of expression?
> Dynamic strings are mainly useful at time of writing readable code
> before compilation.
What does that mean?
> The compiler can choose to convert it into a string
> formatting expression, of course. To efficiently format strings at
> runtime, the best choice (especially
> for safty reasons) is string formatting, not evaluating a dynamic
> string.
So you're suggesting that we should have dynamic strings, but not
actually use dynamic strings. The compiler should just convert them to
regular string formatting.
Why not cut out the middle-man and just use regular string formatting?
--
Steven
More information about the Python-list
mailing list