Hacker News new | past | comments | ask | show | jobs | submit login

If you're interested in this kind of thing, I wrote a python package called "unit-syntax"(https://github.com/ahupp/unit-syntax) that adds physical unit syntax to python:

   >>> speed = 5 meters/second
   >>> (2 seconds) * speed
   10 meter


I'd been using Jupyter notebooks as a calculator for engineering problems and was wishing for the clarity and type safety of real units, but with the succinctness of regular python.

It works in both Jupyter notebooks (with an input transform) and stock python (with an import hook). The actual unit checks and conversions are handled by the excellent `pint` package.




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 '*'.


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...




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: