I need a class that would keep all the Python's functionality of int
class, but make sure its results are within 32-bit integers, just like in C programming language. The type has to be "poisonous" - performing an operation on int and this type should result in returning this type. As suggested in one of the answers to my other question, I used to use numpy.uint32
for this purpose, but it feels too silly to add such a big dependency just for a single, relatively simple, type. How do I achieve that? Here are my attempts so far:
MODULO = 7 # will be 2**32 later on
class u32:
def __init__(self, num = 0, base = None):
print(num)
if base is None:
self.int = int(num) % MODULO
else:
self.int = int(num, base) % MODULO
def __coerce__(self, x):
return None
def __str__(self):
return "<u32 instance at 0x%x, int=%d>" % (id(self), self.int)
def __getattr__(self, x):
r = getattr(self.int, x)
if callable(r):
def f(*args, **kwargs):
ret = r(*args, **kwargs) % MODULO
print("x=%s, args=%s, kwargs=%s, ret=%s" % (x, args, kwargs, ret))
if x not in ['__str__', '__repr__']:
return u32(ret)
return r(*args, **kwargs)
return f
return r
u = u32(4)
print("u/2")
a = u * 2
assert(isinstance(a, u32))
print("\n2/u")
a = 2 * u
assert(isinstance(a, u32))
print("\nu+u")
"""
Traceback (most recent call last):
File "u32.py", line 44, in <module>
a = u + u
File "u32.py", line 18, in f
ret = r(*args, **kwargs) % MODULO
TypeError: unsupported operand type(s) for %: 'NotImplementedType' and 'int'
"""
a = u + u
assert(isinstance(a, u32))