Hacker News new | ask | show | jobs
by chrismorgan 907 days ago
I don’t understand why you’d go to the enormous trouble of extending the syntax when you can write it with perfectly normal syntax. A value-with-unit is, after all, just a scalar multiplied by the unit, and I suppose this would work with the underlying library pint:

   >>> speed = 5*meters/second
   >>> (2 * seconds) * speed
   10 meter
Given the ecosystem problems and other problems extending the syntax gets you, I don’t get why you’d do this at all, when all it gets you is the ability to write ' ' instead of '*'.
2 comments

IMO using operator overloading for this kind of thing makes it hard to read, since I have to be extra careful to mentally parse whether that `*` is a multiplication or units, remember what variables are in scope etc. Notation matters, and if I didn't care about that I'd just write `pint.Quantity(5, "meters/second")` and be done with it. Or more likely, not go to the trouble of using them at all.

> I don’t understand why you’d go to the enormous trouble

But more importantly, it was just really fun to get it working.

> IMO using operator overloading for this kind of thing makes it hard to read, since I have to be extra careful to mentally parse whether that `*` is a multiplication or units

Units are inherently exactly multiplication.

5 meters is:

5 (unitless) * (1) meter

Yes. There are many (infinitely!) ways to write an equivalent expression, most of which are not as clear to read as the standard format.
You neglected to say that this does automatically determine the type instead of type checking as in the article.

You could also use python type hints for this stuff.

Here are some links about units in python:

https://socialcompare.com/en/comparison/python-units-quantit...