[Python-ideas] User-defined literals

Florian Bruhin me at the-compiler.org
Tue Jun 2 21:33:46 CEST 2015


* Andrew Barnert via Python-ideas <python-ideas at python.org> [2015-06-02 12:03:25 -0700]:
> This is a straw-man proposal for user-defined literal suffixes, similar to the design in C++.

I actually had the exact same thing in mind recently, and never
brought it up because it seemed too crazy to me. It seems I'm not the
only one! :D

> Any number or string token followed by a name (identifier) token is currently illegal. This would change so that, if there's no whitespace between them, it's legal, and equivalent to a call to a function named `literal_{name}({number-or-string})`. For example, `1.2d` becomes `literal_d('1.2')`, `1.2_dec` becomes `literal_dec('1.2')`, `"1.2"d` also becomes `literal_d('1.2')`.

I think a big issue is that it's non-obvious syntactic sugar. You
wouldn't expect 1.2x to actually be a function call, and for newcomers
this might be rather confusing...

> 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.

That actually was the use-case I had in mind. I think

    {'spam': 1, 'eggs': 2}_o

is less ugly (and less error-prone!) than

    OrderedDict([('spam', 1), ('eggs': 2)])

Also, it's immediately apparent that it is some kind of dict.

> I've built a quick&dirty toy implementation (at https://github.com/abarnert/userliteralhack). Unlike the real proposal, this only handles numbers, and allows whitespace between the numbers and the names, and is a terrible hack. But it's enough to play with the idea, and you don't need to patch and recompile CPython to use it.

Wow! I'm always amazed at how malleable Python is.

Florian

-- 
http://www.the-compiler.org | me at the-compiler.org (Mail/XMPP)
   GPG: 916E B0C8 FD55 A072 | http://the-compiler.org/pubkey.asc
         I love long mails! | http://email.is-not-s.ms/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 819 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150602/93e7d1c5/attachment.sig>


More information about the Python-ideas mailing list