Bounds checking

Martin De Kauwe mdekauwe at gmail.com
Fri Mar 18 10:24:33 EDT 2011


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



More information about the Python-list mailing list