[Python-ideas] User-defined literals
Steven D'Aprano
steve at pearwood.info
Wed Jun 3 04:52:07 CEST 2015
On Tue, Jun 02, 2015 at 12:03:25PM -0700, Andrew Barnert via Python-ideas wrote:
> I explored the convertible literals a while ago, and I'm pretty sure
> that doesn't work in a duck-typed language. But the C++ design does
> work, as long as you're willing to have the conversion (including the
> lookup of the conversion function itself) done at runtime.
I'm torn. On the one hand, some sort of extensible syntax for literals
would be nice. I say "nice" rather than useful because there are
advantages and disadvantages and there's no way of really knowing
which outweighs the other.
But, really, your proposal is in no way, shape or form syntax for
*literals*, it's a new syntax for an unary postfix operator or function.
The whole point of something being a literal is that it is parsed and
converted at compile time. Now you might (and do) say that worrying
about this is "premature optimization", but call me a pedant if you
like, I don't think we should call something a literal if it's a
runtime function call. Otherwise, we might as well say that
from fractions import Fraction
Fraction(2)
is a literal, in which case I can say your proposal is unnecessary as we
already have user-specified literals in Python.
I can think of some interesting uses for postfix operators, or literals,
or whatever we want to call them:
45°
10!!
23.5d
3d6
35'24"
15ell
I've deliberately not explained what I mean by each of them. You can
probably guess some, or all, but I hope it demonstrates one problem with
this suggestion. Like operator overloading, it risks making code less
clear rather than more.
--
Steve
More information about the Python-ideas
mailing list