PEP 750: Tag Strings For Writing Domain-Specific Languages

I enjoyed playing with this, but I found the first example a bit confusing initially. After reading the “Proposal” section I realized the real power of this feature.

Here’s an example that might demonstrate the power of this a bit more readily:

import re
from typing import Decoded, Interpolation, Pattern


def regex(*args: Decoded | Interpolation) -> Pattern:
    result = []
    for arg in args:
        match arg:
            case Decoded() as decoded:
                result.append(decoded.raw)
            case Interpolation() as interpolation:
                value = interpolation.getvalue()
                result.append(re.escape(value))
    return re.compile(f"{''.join(result)}")

Here’s an example use of that tag (though someone can probably think of a better one):

def find_word(string, word):
    return regex"\b{word}\b".findall(string)

And here’s what it’s effectively equivalent to:

def find_word(string, word):
    return re.findall(rf"\b{re.escape(word)}\b", string)

Fully working code here. Feel free to borrow that code or some variation of it as an example in the PEP.

Note: I tried to come up with an example that used logging or sqlite3 to avoid the common “don’t use f-strings when logging” and “string formatting leads to SQL inejection” issues, but I had trouble due to the inability to use . in the tag. I worked around it with x = cursor.x in this example.


Personal preference note, as someone teaching Python:

I’m torn on the syntax. The use of quotes makes me think “this returns a string” and also seems like it could lead to a challenge in knowing what to look up in a search engine to learn about this syntax.

If backticks or another symbol were used instead of quotes, I could imagine beginners searching for “Python backtick syntax”. But the current syntax doesn’t have a simple answer to “what should I type into Google/DDG/etc. to look this up”.

12 Likes