Storing value with limits in object
Josip
i.i at i.i
Thu Jun 26 12:21:39 EDT 2008
Thanks alot. I'm going to use this with few modifications to tailor it to my
needs.
Thumbs up!
> #!/usr/bin/env python
>
> ## VERSION 2
> ##
> ## changelog:
> ## - Uses inheritance from _Limited
> ## - Added _LimitedLong and llong
> ## - limit choose between int, long, and float
>
> class _Limited(object):
> def setlimits(self, lim):
> ''' Set the limits and if value is not within limit,
> raise ValueError
>
> The lim argument accepts:
> - An instance of _Limited, from which to copy the limits
> - A two-tuple, which specifies the limits i.e. (min, max)
>
> If lim isn't those or lim[0] > lim[1], raise
> InvalidLimitsError
>
> Accepting _Limited instance is just for convenience
> '''
>
> if isinstance(lim, _Limited):
> self.min, self.max = lim.limits
> else:
> try:
> self.min, self.max = lim
> if self.min > self.max: raise ValueError
> except (ValueError, TypeError):
> raise self.InvalidLimitsError, ('limit = %s' %
> str(lim))
>
> if not (self.min < self < self.max):
> raise ValueError, \
> ('val = %s, min = %s, max = %s' % \
> (self, self.min, self.max))
>
> def getlimits(self):
> return (self.min, self.max)
>
> limits = property(getlimits, setlimits)
>
> class _LimitedInt(int, _Limited):
> def __init__(self, value, base = 10):
> int.__init__(value, base)
>
> class _LimitedLong(long, _Limited):
> def __init__(self, value, base = 10):
> long.__init__(value, base)
>
> class _LimitedFloat(float, _Limited):
> def __init__(self, value):
> float.__init__(value)
>
>
> def lint(value, limits, base = None):
> ''' Always Creates _LimitedInt instance, allows the use of base
> '''
> if base:
> ret = _LimitedInt(value, base)
> else:
> ret = _LimitedInt(value)
>
> ret.limits = limits
> return ret
>
> def llong(value, limits, base = None):
> ''' Always Creates _LimitedLong instance, allows the use of base
> '''
> if base:
> ret = _LimitedLong(value, base)
> else:
> ret = _LimitedLong(value)
>
> ret.limits = limits
> return ret
>
> def lfloat(value, limits):
> ''' Always Creates _LimitedFloat instance
> '''
> ret = _LimitedFloat(value)
>
> ret.limits = limits
> return ret
>
> def limit(value, limits):
> ''' Automatically choose between _LimitedInt, _LimitedLong,
> or _LimitedFloat. Cannot use _LimitedInt's/Long's base
> '''
> if isinstance(value, (int, long)):
> try:
> ret = _LimitedInt(value)
> except OverflowError:
> ret = _LimitedLong(value)
> elif isinstance(value, float):
> ret = _LimitedFloat(value)
>
> ret.limits = limits
> return ret
More information about the Python-list
mailing list