On 4/4/22 13:31, David Mertz, Ph.D. wrote:
> You should probably change the thread subject to "All-and-only 7 SI units" if
that's what you mean.
While I'm sure SI would be very useful, I suspect that any system will have to be useful for a much broader audience to
be accepted; given the vast amount of units, I suspect individual libraries will be needed for each area/discipline.
So what hooks does Python need to provide to make such a thing feasible, easy to use, and, eventually if not
immediately, performant?
One idea: have a `unit` attribute, and that attribute keeps track of the units
so far in the operations:
[quick PoC]
class TaggedInt(int):
#
def __new__(cls, *args, unit=None, **kwds):
ti = int.__new__(cls, *args, **kwds)
if unit is None:
unit = ()
elif not isinstance(unit, tuple):
unit = (unit, )
ti.unit = unit
return ti
#
def __mul__(self, other):
other_unit = getattr(other, 'unit', None)
if other_unit is None:
unit = self.unit
else:
unit = self.condense(self.unit, '*', other_unit)
ti = TaggedInt(int.__mul__(self, other), unit=unit)
return ti
#
def __rmul__(self, other):
other_unit = getattr(other, 'unit', None)
if other_unit is None:
unit = self.unit
else:
unit = self.condense(other_unit, '*', self.unit)
ti = TaggedInt(int.__mul__(self, other), unit=unit)
return ti
#
def __repr__(self):
return '%s %s' % (int.__repr__(self), ''.join(str(u) for u in
self.unit))
#
def condense(*args):
result = []
for arg in args:
if isinstance(arg, tuple) and len(arg) == 1:
result.append(arg[0])
else:
result.append(arg)
return tuple(result)
in use:
>>> to_home = TaggedInt(5, unit='km')
>>> to_home
5 km
>>> # home and back
>>> 2 * to_home
10 km
>>> # big square
>>> to_home * to_home
25 km*km
>>> _.unit
('km', '*', 'km')
Beyond that, do we make Python smart enough to, for example, convert `km*km` to `km^2`, or do we let libraries provide
their own functions? I'm inclined to let libraries provide their own, as they could also implement unit conversions as
desired.
--
~Ethan~
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/QCODSL65G6MRAGOA36KY4RPIPOZRARIF/
Code of Conduct: http://python.org/psf/codeofconduct/