[Python-ideas] Custom string prefixes

Steven D'Aprano steve at pearwood.info
Tue May 28 04:09:42 CEST 2013


On 28/05/13 02:26, Göktuğ Kayaalp wrote:
>> I disagree that custom string prefixes make code harder to read. Saying s"ham"
>> costs minutes of confusion over s("ham") is based purely on unfamiliarity,
>> which can be removed over time. Why u"text" rather than make_unicode_string
>> ("text") if the latter is more meaningful?
>
> I concur. And, while we can't know what s("ham") does to the string
> "ham" (print it or get the sum of ord(x) for x in "ham" or add to a
> database) without context, we can understand that some parsing of the
> string is involved when we see s"ham".


Not at all. Since your proposal tells us that the user can define s"" as an arbitrary function, it can do anything.

We already have function call syntax. I don't believe we need two ways to call a function, especially when the second way is so limited (single letter name, one argument, must be a string).


>> * If hooking into this preprocessing could be made easy (via a simple
>>    desugaring, import-hook style, or otherwise). Naively making b"12" call the
>>    function "b" is probably a bad idea, since people using variables called "b"
>>    all the time.
>
> I thought of something like
>
>      >>> string.register_prefix ("x", callable)
>
> where callable expects at least one string argument and returns a
> string. I don't know how apt would this be practically.

This fails your earlier example:

D"1.25" -> Decimal("1.25")


>> If-if-if all that works out, you would be able to completely remove the ("b" |
>> "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB" | "r" | "u" | "R"
>> | "U") from the grammar specification! Not add more to it, remove it! Shifting
>> the specification of all the different string prefixes into a user-land
>> library. I'd say that's a pretty creative way of getting rid of that nasty
>> blob of grammar =D.
>
> Frankly, I never thought of this (simplifying the grammar) :)

And how does that help the reader of the code? Whether all those string prefixes are defined as part of the language grammar, or in a standard library, makes absolutely no difference. They still need to be inserted into builtins so that code that uses them will continue to work.

But now, instead of just a dozen fixed prefixes, you have an unlimited number of potential looks-like-strings-but-actually-are-anything prefixes.



-- 
Steven


More information about the Python-ideas mailing list