Restrict / Limit variable size - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Restrict / Limit variable size (/thread-20458.html) |
Restrict / Limit variable size - mln4python - Aug-12-2019 Can I restrict / limit a variable size in python ? For example, I want to use an int variable which can hold ONLY upto 6 digit values, i.e., -999999 thru 999999. If I assign some value outside this range, I would like to catch the exception. Is this possible ? RE: Restrict / Limit variable size - wavic - Aug-12-2019 if -999999 > number > 999999: # do something RE: Restrict / Limit variable size - snippsat - Aug-12-2019 (Aug-12-2019, 10:04 AM)mln4python Wrote: If I assign some value outside this range, I would like to catch the exception. def clamp(n, min_n=-999999, max_n=999999): if n < min_n: raise Exception(f'To low <{n}> min number is -999999') elif n > max_n: raise Exception(f'To high <{n}> max number is 999999') else: return nTest:
RE: Restrict / Limit variable size - ThomasL - Aug-12-2019 class Limited: def __init__(self, value=None): self._value = value @property def limited(self): return self._value @limited.setter def limited(self, value): if value < -999999: raise ValueError('Value out of bounds: less than -999999') elif value > 999999: raise ValueError('Value out of bounds: greater than 999999') else: self._value = value integer = Limited() # or Limited(0) integer.limited = 1000 print(integer.limited) integer.limited = -11000000
RE: Restrict / Limit variable size - mln4python - Aug-13-2019 (Aug-12-2019, 11:40 AM)ThomasL Wrote:class Limited: def __init__(self, value=None): self._value = value @property def limited(self): return self._value @limited.setter def limited(self, value): if value < -999999: raise ValueError('Value out of bounds: less than -999999') elif value > 999999: raise ValueError('Value out of bounds: greater than 999999') else: self._value = value integer = Limited() # or Limited(0) integer.limited = 1000 print(integer.limited) integer.limited = -11000000 Thanks for the help Thomas! This is what I was looking for... I am able to do additional coding as per my requirement. Thanks again! |