[Python-ideas] datetime.timedelta literals
Pål Grønås Drange
paal.drange at gmail.com
Mon Jun 4 16:59:34 EDT 2018
For the general user-defined literals, here are some example use cases:
Here is how to expose literals:
__literals__ = ['__literal_h__', '__literal_min__', '__literal_s__']
And here is how to import them:
from mymodule import _* # imports all literals from mymodule
# could also be *_ or ** or ~ or __literals__ ?
90_deg # 1.0 in rad
20_°C # 293.15 Kelvin
units.to(20.0_mi, 'km')
e = 1_X + 4_G + 13_M + 180_k # SI scale factors can easily be implemented
p = 3_x - 2_y + 1_z # Coordinate in 3D
M = 4_I # The 4x4 Identity Matrix
p * 2_pi # because it's simpler than 2 * np.pi
p * 11_π # why not
d = 2_sqrt # sqrt(2), or simply 2**(1/2), not a killer argument
h1 = 30_px
h2 = 4_em # sizes for typography
c = 'ffff00'_color # the color yellow
h = 'My header'_h3 # renders <h3>My header</h3> or something
g = 9.81_m_div_ss # that was ugly ...
'More weird examples'_info # log.info(msg)
'2018-06-04'_AD # is a date
'192.168.0.42'_ip4 # why not?
'USER'_os # = os.environ.get(x, '')
# Can have state?
initialize(80) # set default string width to 80 chars
'my string'_c # will now be centralized in 80 chars
'my string'_l # will now be left aligned in 80 chars
'my string'_r # will now be right aligned in 80 chars
If we used, e.g. tilde, we could even use it on function calls
y = fun(x)~dx # differentiations! Like decorators, but on "call time"
I accept that introducing a new symbol has a very high threshold, and
will not go through. I just wanted to mention it.
Yes, we could write all these as easily as function calls,
deg(90)
celsius(20)
center('my string') # or 'my string'.center(80)
But somehow it seems nicer to write 42_km than 12 * pint.UnitRegistry().km
- Pål
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180604/4adb988e/attachment.html>
More information about the Python-ideas
mailing list