[Python-ideas] datetime.timedelta literals
Pål Grønås Drange
paal.drange at gmail.com
Mon Jun 4 06:59:22 EDT 2018
One thing that could solve both this proposal and the aforementioned
SI-proposition by Ken Kundert, could be supporting user-defined
literals. Suppose that __litXXX___ would make XXX a literal one could
use as a suffix for numbers and strings (and lists, dicts, sets?).
A user-defined literal could be defined as __lit<insert literal>__,
though I don't know how to import it.
Anything without leading underscore could be preserved for the standard
library:
# In the standard library:
def __litj__(x):
return complex(0, x)
# The above example would make 2+3j work as expected
# In the datetime module
def __lit_h__(x):
return timedelta(hours=x)
def __lit_min__(x):
return timedelta(minutes=x)
# In the Pint (units) module for dimensional analysis
def __lit_km__(x):
return x * pint.UnitRegistry().km
# It wouldn't be limited to numbers
def __lit_up__(x):
return x.upper()
s = 'literal'_up # s = LITERAL
# The _(x) from Django could be written
def __lit_T__(x):
return translate(x)
s = 'literal'_T # s = translate('literal')
# Heck, it could even be written as (abusing(?) notation)
def __lit___(x):
return translate(x)
s = 'literal'_ # s = translate('literal')
If we want to abuse the literals more, one could make
def __lit_s__(lst):
"""Makes a list into a sorted list"""
return sortedlist(lst)
heap = []_s # heap is of type sortedlist
- Pål
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180604/8123b29a/attachment.html>
More information about the Python-ideas
mailing list