Extending Python’s int type to accept only values within a given range
- by igor
I would like to create a custom data type which basically behaves like an ordinary int, but with the value restricted to be within a given range. I guess I need some kind of factory function, but I cannot figure out how to do it.
myType = MyCustomInt(minimum=7, maximum=49, default=10)
i = myType(16) # OK
i = myType(52) # raises ValueError
i = myType() # i == 10
positiveInt = MyCustomInt(minimum=1) # no maximum restriction
negativeInt = MyCustomInt(maximum=-1) # no minimum restriction
nonsensicalInt = MyCustomInt() # well, the same as an ordinary int
Any hint is appreciated. Thanks!