[Python-Dev] Adding syntax for units of measure
Georg Brandl
g.brandl at gmx.net
Tue Jun 23 19:40:28 CEST 2009
Tobias C. Rittweiler schrieb:
> Hi!
>
> Has anyone added special syntax to allow writing numeric literals with
> physical units? So you can write 12m + 34cm, and would get 12.34m.
>
> My question is how would you modify the BNF the most sensible way to
> allow for this? The above example is simple, but think of 42 km/h.
>
> (For my purposes, modifying the BNF is perfectly reasonable, but if you
> can depict a good, and convenient!, way that would not result in
> modifying it, I'd like to hear it, too.)
Hi,
normally you wouldn't add units to the language itself. When using them
programmatically, it should be no effort to use a class that represents a
quantity with unit. This can be made as easy as making "m" an object of
that type, so that you only need to type "2*m" to get two meters.
For the interactive shell, using a wrapper that allows simplified input is
also a possibility, like IPython's "-profile physics" mode, or something like
http://bitbucket.org/birkenfeld/phsh/ which allows you to write
>>> `1 m` + `12 cm`
1.12 m
cheers,
Georg
More information about the Python-Dev
mailing list