[Python-ideas] Units in type hints

Skip Montanaro skip.montanaro at gmail.com
Fri May 15 18:07:58 CEST 2015


On Fri, May 15, 2015 at 10:28 AM, Chris Angelico <rosuav at gmail.com> wrote:
> Dividing a unit-aware value by a scalar shouldn't be an error. "I
> have an A4 sheet of paper. If I fold it in half seven times, how big
> will it be?" => 210mm*297mm/(2**7) == 487.265625 mm^2.

Here's this example using the magnitude module:

>>> from magnitude import mg
>>> a4 = mg(210, "mm") * mg(297, "mm")
>>> a4
<magnitude.Magnitude instance at 0x15de9e0>
>>> # Invalid - units are actually mm^2
>>> a4.ounit("mm")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/lib/python2.7/site-packages/magnitude.py", line 397, in ounit
    (self.out_factor.unit, self.unit))
MagnitudeError: Inconsistent Magnitude units: [1, 0, 0, 0, 0, 0, 0, 0,
0], [2, 0, 0, 0, 0, 0, 0, 0, 0]
>>> a4.ounit("mm2")
<magnitude.Magnitude instance at 0x15de9e0>
>>> a4.ounit("mm2").toval()
62370.0
>>> a4.toval()
62370.0
>>> 210 * 297
62370
>>> # Not sure why dimensionless / isn't supported
>>> folded7x = a4 * (1/2**7)
>>> folded7x
<magnitude.Magnitude instance at 0x15f00e0>
>>> folded7x.ounit("mm2").toval()
487.265625

Skip


More information about the Python-ideas mailing list