Add ability to define literal prefixes in classes

For example, to have a raw string, you can use the prefix r and to have a hexadecimal number, you can use the prefix 0x. I suggest being able to do something like this:

class EnhancedStr(str, prefix_str = 'e'):
    # code goes here

which would allow you to instantiate the class by doing e"string to instantiate". I also suggest allowing a similar thing for numbers and other data types.

When an idea emerges similar to one rejected earlier, core devs (and others) often ask what is different or what has changed. History of relevance here:

Custom string prefixes

Tagged strings in python

Also, they ask for compelling use-cases (like the html one cited).

Be aware that neither of these changes the type of the object you get back. Raw string literals and hex integer literals result in the exact same string and integer objects as any others do. The only string prefix that changes the type is b"..." for a byte string.

Creation of new types of literal requires either some sort of import hook, or a generalized system whereby e"string to instantiate" actually calls some sort of registered transformation function, at which point it’s not very different from e("string to instantiate") which already works.

This has already been proposed: Allow for arbitrary string prefix of strings - #6 by jimbaker and is actively being worked on: GitHub - jimbaker/tagstr: This repo contains an issue tracker, examples, and early work related to PEP 999: Tag Strings

2 Likes