Bounds checking
Dan Stromberg
drsalists at gmail.com
Fri Mar 18 19:24:40 EDT 2011
Actually, I'd probably create a class with 3 arguments - an initial value, a
lower bound, and an upper bound, give it a _check method, and call _check
from the various operator methods. The class would otherwise impersonate an
int.
In code that isn't performance-critical, it's better to check for errors on
a level that seems excessive to many; this is how I like to program - it
tends to stop bugs in their tracks, rather than allowing them to manifest
somewhere far away, elsewhere in the code, yielding a potentially
time-consuming bug chase. So I'll have if's and asserts checking
assumptions everywhere - at the beginning of a callable, at the end, in the
middle - inspired by Eiffel's heavy assumption checking.
Python code doesn't need to be troublesome. I'm told this is how a famous
chess engine (was it Crafty?) got pretty much all of its bugs out.
Or if things don't need to be in the correct range every step of the way (or
rather, if they must be able to temporarily step outside their bounds), then
you could make self._check() be self.check(), and call it externally on an
as-needed basis instead.
Performance-oriented programming is fun, but not all programming is
performance-oriented, and shouldn't be treated as though it is.
On Fri, Mar 18, 2011 at 7:24 AM, Martin De Kauwe <mdekauwe at gmail.com> wrote:
> Hi,
>
> if one has a set of values which should never step outside certain
> bounds (for example if the values were negative then they wouldn't be
> physically meaningful) is there a nice way to bounds check? I
> potentially have 10 or so values I would like to check at the end of
> each iteration. However as the loop is over many years I figured I
> probably want to be as optimal as possible with my check. Any
> thoughts?
>
> e.g. this is my solution
>
> # module contain data
> # e.g. print state.something might produce 4.0
> import state as state
>
> def main():
> for i in xrange(num_days):
> # do stuff
>
> # bounds check at end of iteration
> bounds_check(state)
>
>
> def bounds_check(state):
> """ check state values are > 0 """
> for attr in dir(state):
> if not attr.startswith('__') and getattr(state, attr) < 0.0:
> print "Error state values < 0: %s" % (attr)
> sys.exit()
>
> if __name__ == "__main__":
> sys.exit(main())
>
> thanks
>
> Martin
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110318/00e31d66/attachment-0001.html>
More information about the Python-list
mailing list