Adding property to int value in python

I have a value that is commonly used throughout my code in different units. For example. representing the size of the buffer in the amount of BYTES, but in many places referring to the size as KB or as MB (this is just an example, not my real use case).

For elegance and ease of use, I want to avoid explicit conversions (e.g. size/1024 or b_to_mb(size) ) because they are needed in many different places.

I thought I could achieve this with properties, which simplifies the conversion ( x.kb or x.mb ), and also causes the caller to not know the units of the stored actual value.

My code is as follows:

 class BufferSize(int): @property def b(self): return int(self) @property def kb(self): return self.b / 1024 @property def mb(self): return self.kb / 1024 

This works until I use arithmetic operators:

 s = BufferSize(500000) s.kb => 488.28125 # ok s.mb => 0.476837158203125 # ok type(s + BufferSize(0)) => int # type lost... 

Is there a way to ensure that arithmetic operations preserve type? That is, in addition to redefining each of them?

Or maybe another and better way to solve the original problem?

+7
operators python inheritance properties int
source share
1 answer

Well, these are not as many re-implementations as wrap / cast results of magic int methods, at least those that return int s .. All of them, unfortunately. I wonder if you can not use a decorator or metaclass to speed this up.

 class BufferSize(int): @property def b(self): return int(self) @property def kb(self): return self.b / 1024 @property def mb(self): return self.kb / 1024 def __add__(self, *args, **kwds): return BufferSize(super(BufferSize, self).__add__(*args, **kwds)) v = BufferSize(1) + BufferSize(2) print v, type(v) 

exit:

 3 <class '__main__.BufferSize'> 

I also thought about adding the property directly to the int itself, but a quick test violated this.

 >>> int.b = "b" 

exit:

  can't set attributes of built-in/extension type 'int' 
+2
source share

All Articles