[Python-ideas] Custom string prefixes

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


On 28/05/13 01:51, Haoyi Li 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?

For backward compatibility, of course. u"text" only because Python 1.x didn't have Unicode strings.

Of course people have to learn language features, and when reading an unfamiliar language you may be unfamiliar with the semantics of a specific function call. But it's much easier to guess that:

Decimal("1.25")

calls a function called "Decimal" with the string "1.25" as the single argument, since this is notation shared by nearly all mainstream programming languages. Then you have a good place to start: search for Decimal, and see where it is defined. On the other hand, one needs to be intimately familiar with the code-base to know that:

D"1.25"

means exactly the same thing. It's radically different from most programming languages, and it doesn't look like a function call even though it is a function call. Why have two ways to call the function Decimal just to save a pair of parentheses?

Python includes Unicode literals so we can write strings in the natural way. In Python 3, where the u prefix is no longer required, I can say:

equation = "2πθ"

and it works perfectly naturally, without needing to mess around with bytes and encodings. This is important for strings, since they are a fundamental data type, but not every data type needs to have compiler support, and not every function is so important that saving two parentheses is worth the reduction in readability.



-- 
Steven


More information about the Python-ideas mailing list