Skip to content

Instantly share code, notes, and snippets.

@imposeren
Created May 13, 2019 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imposeren/5501a54a2ea0785cac57b104df9218c0 to your computer and use it in GitHub Desktop.
Save imposeren/5501a54a2ea0785cac57b104df9218c0 to your computer and use it in GitHub Desktop.
class MutableInt:
def __init__(self, value):
self.value = value
def __iadd__(self, other):
self.value += other
return self
def __imul__(self, other):
self.value *= other
return self
def magic_op(self, method, other):
cls = type(self)
if isinstance(other, cls):
other = other.value
res = getattr(self.value, method)(other)
if isinstance(res, int) and not isinstance(res, bool):
res = cls(res)
return res
def __int__(self):
return self.value
def __add__(self, other):
return self.magic_op('__add__', other)
def __mul__(self, other):
return self.magic_op('__mul__', other)
def __eq__(self, other):
return self.magic_op('__eq__', other)
# other methods like __sub__, __pow__, etc are required for full compatibility with ints:
# https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types
a = MutableInt(1)
b = MutableInt(2)
a = b
print(a == 2) # True
b += 1
print(a.value) # 3
print(b.value) # 3
print(a == 3) # True
print(b == 3) # True
a *= 4
print(a == 12) # True
print(b == 12) # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment