meade meade - 1 year ago 114
Python Question

Best practice for Python Assert

  1. Is there a performance or code maintenance issue with using
    as part of the standard code instead of using it just for debugging purposes?


    assert x >= 0, 'x is less than zero'

    better or worse than

    if x < 0:
    raise Exception, 'x is less than zero'

  2. Also, is there any way to set a business rule like
    if x < 0 raise error
    that is always checked without the
    so, if at anytime throughout the code
    is less than 0 an error is raised, like if you set
    assert x < 0
    at the start of a function, anywhere within the function where
    becomes less then 0 an exception is raised?

Answer Source

To be able to automatically throw an error when x become less than zero throughout the function. You can use class descriptors. Here is an example:

class LessThanZeroException(Exception):

class variable(object):
    def __init__(self, value=0):
        self.__x = value

    def __set__(self, obj, value):
        if value < 0:
            raise LessThanZeroException('x is less than zero')

        self.__x  = value

    def __get__(self, obj, objType):
        return self.__x

class MyClass(object):
    x = variable()

>>> m = MyClass()
>>> m.x = 10
>>> m.x -= 20
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "", line 7, in __set__
    raise LessThanZeroException('x is less than zero')
LessThanZeroException: x is less than zero
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download