Best practice for using assert? Best practice for using assert? python python

Best practice for using assert?


Asserts should be used to test conditions that should never happen. The purpose is to crash early in the case of a corrupt program state.

Exceptions should be used for errors that can conceivably happen, and you should almost always create your own Exception classes.


For example, if you're writing a function to read from a configuration file into a dict, improper formatting in the file should raise a ConfigurationSyntaxError, while you can assert that you're not about to return None.


In your example, if x is a value set via a user interface or from an external source, an exception is best.

If x is only set by your own code in the same program, go with an assertion.


"assert" statements are removed when the compilation is optimized. So, yes, there are both performance and functional differences.

The current code generator emits no code for an assert statement when optimization is requested at compile time. - Python 2 Docs Python 3 Docs

If you use assert to implement application functionality, then optimize the deployment to production, you will be plagued by "but-it-works-in-dev" defects.

See PYTHONOPTIMIZE and -O -OO


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):    passclass 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.__xclass MyClass(object):    x = variable()>>> m = MyClass()>>> m.x = 10>>> m.x -= 20Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "my.py", line 7, in __set__    raise LessThanZeroException('x is less than zero')LessThanZeroException: x is less than zero