Adding a simple way to create string prefixes

Adding a simple way to create string prefixes.

My proposition is to add a way to make new strings prefixes more easily:

If you have a class like this:

class MyClass:
    def __init__(self, value):
        ...

The __init__ method of the class must’ve only one positional argument.

You can add a decorator to the class:

@prefix(“p”)
class MyClass:
    def __init__(self, value):
        ...

So each time you write something like this:

string = p”hello”

Python will interpret this line as:

string = MyClass(“hello”)

This can improve the clarity of the code, making it more readable and more explicit when you need a repetitive type.

PEP 750: Tag Strings For Writing Domain-Specific Languages

:slightly_smiling_face:

2 Likes

My idea is more about the implementation, but thank you.

With PEP750, you can write your own prefix decorator:

def prefix(name):
    def decorator(func):
        globals()[name] = func
        return func
    return decorator

Trying it out on their jupyterlite:

Screenshot from 2024-08-12 09-01-50

You are proposing the ability to change the syntax of Python at runtime. Very few languages do this, as it makes parsing more complicated, and it’s especially incongruous for a language like Python which has traditionally strongly constrained its grammar in the name of simplifying parsing.

(Prior to the PEG parser, the grammar was intentionally limited to an LL(1) grammar. I believe that’s one reason why a if condition else b was chosen over if condition then a else b for the conditional expression, because the latter would require additional–unlimited?–lookahead to distinguish from an ordinary if statement.)

1 Like