[Python-ideas] datetime.timedelta literals

Stephen J. Turnbull turnbull.stephen.fw at u.tsukuba.ac.jp
Mon Jun 4 04:26:01 EDT 2018


Pål Grønås Drange writes:

 > That's good to hear, but if you don't mind asking, is your lack of
 > support because you use timedelta "programatically" instead of
 > hard-coded time units, or is there a different (or more) reason(s)?

Speaking for myself, not for Paul, I guess my big objection would be
that there would be too many collisions with other interpretations.
Eg, does "5m" mean "5 minutes", "5 meters", or "the number 0.005"?  Or
perhaps "5 minutes of arc"?  If you want something close to a literal,
you can take the approach used by Decimal of initializing from a
string:

def make_timedelta(s):
    if s[-1] == "m":
        return timedelta(0, 60*int(s[:-1]), 0)
    # and so on

TD = make_timedelta        # alias for brevity
td = TD("5m")

This is more to type, and less readable (if you have a dominant
interpretation for the "unit"!), but more flexible, and more readable
(if you have multiple dimensioned types around -- if you forget what
the unit means in this context, at least you still know the type of
the object).

It occurs to me that when we have more experience with typed
variables, it might be worth revisting this, because then you could
write

td: datetime.timedelta
td = 5m

I personally would still be against it because there's too much
potential for collision and I don't see why we'd privilege time units
over other units or SI multipliers.  I'm also sure that you'd get some
degree of opposition from the people who really want types to be
optional and fear any other feature that depends on typing as a
"Trojan horse" to turn Python into a strictly-typed language.

Steve


More information about the Python-ideas mailing list