Bounds checking
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Mar 19 03:46:44 EDT 2011
On Fri, 18 Mar 2011 15:35:40 -0700, Martin De Kauwe wrote:
>> Don't check for bounds, fix any bug in the code that would set your
>> values out of bounds and use asserts while debugging.
>>
>>
> whilst that is a nice idea in practice this just is not a practical
> solution.
Sorry, are you trying to say that it is not practical to write correct
code that isn't buggy? Well, you're honest, at least, still I can't help
but feel that you're admitting defeat before even starting.
>> Otherwise if you really need dynamic checks, it will cost you cpu, for
>> sure.
>
> Yes I agree and I hadn't decided whether to add it or not as there
> aren't any current issues. However I can see that the check would
> overall be safer. I was just wondering if there was some super smartie
> pants solution :P
Make each of the attributes a computed attribute with a setter that
raises an exception if you try to store a negative value. That way each
attribute is responsible for ensuring that itself is never negative.
Here's a toy example:
>>> class Demo(object):
... def __init__(self, x):
... self.x = x
... def _getx(self):
... return self._x
... def _setx(self, value):
... if value < 0:
... raise ValueError('attempt to set x to negative value')
... self._x = value
... x = property(_getx, _setx)
...
>>> d = Demo(-42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
File "<stdin>", line 8, in _setx
ValueError: attempt to set x to negative value
>>> d = Demo(42)
>>> d.x
42
>>> d.x = -23
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in _setx
ValueError: attempt to set x to negative value
>>> d.x = 23
>>> d.x
23
--
Steven
More information about the Python-list
mailing list