Skip to content

Instantly share code, notes, and snippets.

@Curiouspaul1
Last active June 17, 2024 01:25
Show Gist options
  • Save Curiouspaul1/e3605f28d9d93b16e1baadcb031eda55 to your computer and use it in GitHub Desktop.
Save Curiouspaul1/e3605f28d9d93b16e1baadcb031eda55 to your computer and use it in GitHub Desktop.
A `Range` type in python that ensures that a value is within a certain range of positive values (not inclusive of the last)
ranged_int = type('ranged_int', (int,), {})
# # define a type alias
# type RangedInt = int
class RangeObj:
def __new__(self, floor, ceil):
if ceil <= floor or floor >= ceil:
raise ValueError(
"Invalid format for type <RangedInt>:"
" must specify correct `ceil` and `floor` values"
" ceil cannot be less than or equal to floor and vice versa"
)
return type('IntRange', (), {'ceil': ceil, 'floor': floor})
class RangedInt(int):
def __new__(cls, range_object: RangeObj, value: int) -> RangeObj:
if value < range_object.floor or value >= range_object.ceil:
raise ValueError(
"Invalid number specified, value cannot be greater"
" than or equal to <RangeObj.ceil> or less"
" than <RangeObj.floor>"
)
return super().__new__(cls, value)
# test
R1 = RangeObj(5, 10)
x1 = RangedInt(R1, 9)
print(x1) # prints the value as expected
x2 = RangedInt(R1, 12) # raises an ValueError exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment