|
from weakref import WeakValueDictionary |
|
import pytest |
|
|
|
class GenericWrappedBoundedInt(int): |
|
|
|
MAX_VALUE: int = 0 |
|
|
|
__concrete_bounded_ints__ = WeakValueDictionary() |
|
|
|
def __new__(self, value: int): |
|
inst = super().__new__(self, value % self.MAX_VALUE) |
|
return inst |
|
|
|
def __repr__(self) -> str: |
|
return f"<BoundedInt[MAX_VALUE={self.MAX_VALUE}]: {super().__repr__()}>" |
|
|
|
def __str__(self) -> str: |
|
return repr(self) |
|
|
|
def __class_getitem__(cls, idx=MAX_VALUE): |
|
if not isinstance(idx, int): |
|
raise TypeError(f"cannot make `BoundedInt[{idx}]`") |
|
|
|
if idx not in cls.__concrete_bounded_ints__: |
|
class ConcreteBoundedInt(cls): |
|
MAX_VALUE = idx |
|
cls.__concrete_bounded_ints__[idx] = ConcreteBoundedInt |
|
|
|
return cls.__concrete_bounded_ints__[idx] |
|
|
|
# here you got to write many operator overrides: +, -, etc. |
|
|
|
def test_bounded_int(): |
|
|
|
bounded_twenty_int_value = GenericWrappedBoundedInt[20](11) |
|
|
|
bounded_twenty_int_value += 10 # return type here is int |
|
with pytest.raises(AssertionError): |
|
assert bounded_twenty_int_value == (11 + 10) % 20 # (11 + 10 = 21) % 20 = 1 |
|
assert bounded_twenty_int_value == 21 # 11 + 10 = 21 |
|
assert isinstance(bounded_twenty_int_value, int) |
|
assert not isinstance(bounded_twenty_int_value, GenericWrappedBoundedInt[20]) |
|
|
|
bounded_twenty_int_value -= 22 |
|
with pytest.raises(AssertionError): |
|
assert bounded_twenty_int_value == (21 - 22) % 20 # (21 - 22 = -1) % 20 = 19 |
|
assert bounded_twenty_int_value == -1 # 21 - 22 = -1 |
|
assert isinstance(bounded_twenty_int_value, int) |
|
assert not isinstance(bounded_twenty_int_value, GenericWrappedBoundedInt[20]) |
|
|
|
def benchmark(): |
|
import time |
|
bounded_twenty_int_value = GenericWrappedBoundedInt[20](11) |
|
start_time = time.time() |
|
for _ in range(100_000): |
|
bounded_twenty_int_value += 10 |
|
end_time = time.time() |
|
print(f"Benchmark completed in {end_time - start_time:.50f} seconds") |
|
print(f"Final value: {bounded_twenty_int_value}") |
|
|
|
if __name__ == '__main__': |
|
benchmark() |