[Python-ideas] datetime.timedelta literals

Rob Cliffe rob.cliffe at btinternet.com
Mon Jun 4 19:13:36 EDT 2018



On 04/06/2018 19:50, Kyle Lahnakoski wrote:
>
>
> Maybe the Python parser can be made to add an implied multiplication 
> between a-number-followed-directly-by-a-variable-name. If so, then I 
> could write:
>
> (2.5HOUR - 14MINUTE + 9300MILLISECOND).total_seconds()
>
>
This strikes me as quite a nifty idea, if the implied multiplication 
calls (by default) __rmul__ on the second operand.  A ridiculously 
simple example:

 >>> import datetime
 >>> class D(object):
         def __rmul__(self, LHS):
                     return datetime.timedelta(days=LHS)
 >>> # Possibly some magic to make D a singleton class
 >>> d=D()
 >>> 2*d    # Works now
datetime.timedelta(2)
 >>> 2d     # Does not work now
datetime.timedelta(2)

There would, sadly,  be a conflict with
     floating literals such as "2e3"
     hex literals such as 0XB
     complex literals such as 4j
     numeric literals such as 1_234
     any others I haven't thought of
So the parser would have to give priority to such existing, valid forms.

Rob Cliffe


More information about the Python-ideas mailing list