Extending Python’s int type to accept only values within a given range
        Posted  
        
            by igor
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by igor
        
        
        
        Published on 2010-04-14T05:48:20Z
        Indexed on 
            2010/04/14
            5:53 UTC
        
        
        Read the original article
        Hit count: 722
        
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!
© Stack Overflow or respective owner