[Python-ideas] String interpolation for all literal strings

Nick Coghlan ncoghlan at gmail.com
Thu Aug 6 15:01:15 CEST 2015


On 6 August 2015 at 17:25, Nathaniel Smith <njs at pobox.com> wrote:
> On Wed, Aug 5, 2015 at 11:27 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> Fortunately, using "!" as a string prefix doesn't preclude using it
>> for the case you describe, or even from offering a full compile time
>> macro syntax as "!name(contents)".
>>
>> It's one of the main reasons I like it over "$" as the marker prefix -
>> it fits as a general "compile time shenanigans are happening here"
>> marker if we decide to go that way in the future, while "$" is both
>> heavier visually and very specific to string interpolation.
>
> I guess it's a matter of taste -- string interpolation doesn't strike
> me as particularly compile-time-shenanigany in the way that macros
> are, given that you could right now implement a function f such that
>
>   f("...")
>
> would work exactly like the proposed
>
>   f"..."
>
> with no macros needed. But it's true that both can easily coexist; the
> only potential conflict is in the aesthetics.

You can write functions that work like the ones I described as well.
However, they all have the same problem:

* you can't restrict them to "literals only", so you run a much higher
risk of code injection attacks
* you can only implement them via stack walking, so name resolution
doesn't work right. You can get at the locals and globals for the
calling frame, but normal strings are opaque to the compiler, so
lexical scoping doesn't trigger properly

By contrast, the "compile time shenanigans" approach lets you:

* restrict them to literals only, closing off the worst of the
injection attack vectors
* make the construct transparent to the compiler, allowing lexical
scoping to work reliably

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list