PEP 750: Tag Strings For Writing Domain-Specific Languages

>>> "Hello {name}".format(name="World")
'Hello World'

But the string.format method only superficially resembles fstrings, no? It’s much simpler.

That’s correct, but like you already said why would you want to evaluate (potentially) untrusted code? Eval really is dangerous | Ned Batchelder
There would also be no way to check for syntax errors in advance.

Yes, I kind of realized that. The fact that fstrings really can include any code de facto means that they’re not suitable for “external loading”, and the same goes for tstrings. I guess str.format() or a dedicated templating package like Jinja are better alternatives for what I had in mind. Thanks :slight_smile:

3 Likes

A question: what will be the advantage of using a Template string for SQL vs prepared statements?

It’s similar to the benefit f-strings offer over using string formatting on literal strings: the reader doesn’t have to mentally interpolate the values into their corresponding locations.

There’s also a slight performance advantage, since the template gets parsed into text segments and interpolation fields at compile time rather than runtime (again similar to f-strings vs dynamic string formatting).

https://docs.python.org/3/library/string.html#custom-string-formatting is the stdlib tool for processing format strings at runtime.

With PEP 750, it’s feasible to write a custom formatter that produces a template object placeholder field values from a regular string.

3 Likes

Apologies in advance, I haven’t been following this closely.

But hopefully it is a straight forward question.

I see that string-prefixes are being specialised for formatting only.

However, will it be possible to get the raw string?

as per example in jupyterlite:

def greet(*args):
    print(args)

greet"Hello ?? {a:1}"    # (DecodedConcrete('Hello ?? '), InterpolationConcrete(...))

However, what if I don’t need to format, all I need is syntactic convenience. I.e.:

def greet(string):
    print(string)

greet"Hello ?? {a:1}"    # "Hello ?? {a:1}"

Wouldn’t it be good (if it is not possible by current plan) to not limit this to string formatting, but have a more general pass-through layer first, which is then specialised to string formatting?

The latest proposal completely dropped the custom tag syntax. The PEP should be updated and a new thread created, continuing this one is just going to cause more and more confusion.

13 Likes

Yes please. When I saw there were over 300 posts I started to panic.

4 Likes

We’re currently doing some more minor changes to the PEP. There’ll be a new version out soon, along with a new Discourse thread.

6 Likes

We’ve just posted an update to PEP 750 and (phew!) a new Discourse thread.

Hop on in! :smile:

2 Likes