Bounds checking

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Mar 18 11:01:13 EDT 2011


Martin De Kauwe 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
>   
Don't check for bounds, fix any bug in the code that would set your 
values out of bounds and use asserts while debugging.

Otherwise if you really need dynamic checks, it will cost you cpu, for 
sure. Howeverver you could for instance override the __setatttr__ of 
state object, and call the attribute's associated function.

class State(object):
    funcTable = {
       'foo': lambda x: x >= 0.0
    }
   
    def __init__(self):
       self.foo = 0

    def __setattr__(self, attribute, value):
       if not self.funcTable.get(attribute, lambda x: True)(value):
           sys.exit('error out of bound')
       return object.__setattr(self, attribute, value)


Untested, however it's just an idea. I'm not even sure that would be 
less cpu consuming :D
That way only attributes in functable execute a (cpu consuming ?) test 
function, all other attributes will execute 'lambda x: True'.

The check occurs everytime you set an attribute however.

JM



More information about the Python-list mailing list