I need to keep track of units on float and int values in Python, but I don’t want to use an external package like magnitude or others, because I don’t need to perform operations on the values. Instead, all I want is to be able to define floats and ints that have a unit attribute (and I don’t want to add a new dependency for something this simple). I tried doing:
class floatwithunit(float):
__oldinit__ = float.__init__
def __init__(self, *args, **kwargs):
if 'unit' in kwargs:
self.unit = kwargs.pop('unit')
self.__oldinit__(*args, **kwargs)
But this doesn’t work at all:
In [37]: a = floatwithunit(1.,unit=1.) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/tom/<ipython console> in <module>() TypeError: float() takes at most 1 argument (2 given) Any suggestions?
Advertisement
Answer
You might be looking for something like this:
class UnitFloat(float):
def __new__(self, value, unit=None):
return float.__new__(self, value)
def __init__(self, value, unit=None):
self.unit = unit
x = UnitFloat(35.5, "cm")
y = UnitFloat(42.5)
print x
print x.unit
print y
print y.unit
print x + y
Yields:
35.5 cm 42.5 None 78.0