[Python-ideas] User-defined literals

Nathaniel Smith njs at pobox.com
Tue Jun 2 21:40:50 CEST 2015


On Tue, Jun 2, 2015 at 12:03 PM, Andrew Barnert via Python-ideas
<python-ideas at python.org> wrote:
> This is a straw-man proposal for user-defined literal suffixes, similar to the design in C++.
>
> In the thread on decimals, a number of people suggested that they'd like to have decimal literals. Nick Coghlan explained why decimal.Decimal literals don't make sense in general (primarily, but not solely, because they're inherently context-sensitive), so unless we first add a fixed type like decimal64, that idea is a non-starter. However, there was some interest in either having Swift-style convertible literals or C++-style user-defined literals. Either one would allow users who want decimal literals for a particular app where it makes sense (because there's a single fixed context, and the performance cost of Decimal('1.2') vs. a real constant is irrelevant) to add them without too much hassle or hackery.

Are there any use cases besides decimals? Wouldn't it be easier to
just add, say, a fixed "0d" prefix for decimals?

0x1001  # hex
0b1001  # binary
0d1.001 # decimal

> Similarly, this idea could be extended to handle all literal types, so you can do `{'spam': 1, 'eggs': 2}_o` to create an OrderedDict literal, but I think that's ugly enough to not be worth proposing. (A prefix looks better there... but a prefix doesn't work for numbers or strings. And I'm not sure it's unambiguously parseable even for list/set/dict.) Plus, there's the problem that comprehensions and actual literals are both parsed as displays, but you wouldn't want user-defined comprehensions.

Also there's the idea floating around of making *all* dicts ordered
(as PyPy has done), which would be much cleaner if it can be managed,
so I'm guessing that would have to be tried and fail before any new
syntax would be added for this use case.

-n

-- 
Nathaniel J. Smith -- http://vorpus.org


More information about the Python-ideas mailing list