-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutint.py
More file actions
72 lines (56 loc) · 1.76 KB
/
mutint.py
File metadata and controls
72 lines (56 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""
A mutable integer type
"""
from functools import total_ordering
@total_ordering
class MutInt:
"""
Object representing a mutable integer. The `value` property holds the underlying value.
"""
__slots__ = ["value"]
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
def __repr__(self):
return f"MutInt({self.value!r})"
def __format__(self, fmt):
return format(self.value, fmt)
def __add__(self, other):
if isinstance(other, MutInt):
return MutInt(self.value + other.value)
elif isinstance(other, int):
return MutInt(self.value + other)
else:
return NotImplemented
__radd__ = __add__ # Handle int + MutInt
# Implement in-place add for real mutability
# Otherwise __add__ is called returning a new instance
def __iadd__(self, other):
if isinstance(other, MutInt):
self.value += other.value
return self
elif isinstance(other, int):
self.value += other
return self
else:
return NotImplemented
def __eq__(self, other):
if isinstance(other, MutInt):
return self.value == other.value
elif isinstance(other, int):
return self.value == other
else:
return NotImplemented
def __lt__(self, other):
if isinstance(other, MutInt):
return self.value < other.value
elif isinstance(other, int):
return self.value < other
else:
return NotImplemented
def __int__(self):
return self.value
def __float__(self):
return float(self.value)
__index__ = __int__ # Allow use as an index