[Python-ideas] User-defined literals

Andrew Barnert abarnert at yahoo.com
Fri Jun 5 00:43:53 CEST 2015


On Jun 4, 2015, at 14:45, Chris Angelico <rosuav at gmail.com> wrote:
> 
>> On Fri, Jun 5, 2015 at 7:34 AM,  <random832 at fastmail.us> wrote:
>>> On Thu, Jun 4, 2015, at 17:23, Chris Angelico wrote:
>>> Huh. Does that imply that Brython has to construct a brand-new integer
>>> object for absolutely every operation and constant, in case someone
>>> monkeypatched something? Once integers (and other built-in types) lose
>>> their immutability, they become distinguishable:
>>> 
>>> x = 2
>>> monkey_patch(x)
>>> y = 2
>> 
>> Er, we're talking about monkey-patching the int *class* (well, the
>> complex class, but the same idea applies), not an individual int object.
> 
> Ah okay. Even so, it would be very surprising if "1+2" could evaluate
> to anything other than 3.

It's surprising that int('3') could evaluate to 4, or that print(1+2) could print 4, or that adding today and a 1-day timedelta could give you a date in 1918, or that accessing sys.stdout could play a trumpet sound and then read a 300MB file over the network, but there's nothing in the language stopping you from shadowing or replacing or monkeypatching any of those things, there's just your own common sense, and your trust in the common sense of other people working on the code with you.

And, getting this back on point: That also means there would be nothing stopping you from accidentally or maliciously redefining literal_d to play a trumpet sound and then read a 300MB file over the network instead of giving you a Decimal value, but that's not a problem the language has to solve, any more than it's a problem that you can replace int or print or sys.__getattr__.

The fact that people might overuse user-defined literals (e.g., I think using it for units, like the _ms suffix that C++'s timing library uses, is a bad idea), that's potentially a real problem. The fact that people might stupidly or maliciously interfere with some-other-user's-defined literals is not. Yes, you can surprise people that way, but Python already gives you a lot of much easier ways to surprise people. Python doesn't have a secure loader or enforced privates and constants or anything of the sort; it's designed to be used by consenting adults, and that works everywhere else, so why wouldn't it work here?


More information about the Python-ideas mailing list