使用断言的最佳实践? [英] Best practice for using assert?

查看:50
本文介绍了使用断言的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 使用 assert 作为标准代码的一部分而不是仅用于调试目的是否存在性能或代码维护问题?

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

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

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

  • 此外,如果x<0引发错误总是不使用 try/except/finally 进行检查,因此,如果在整个代码 x 中的任何时候小于0都会引发错误,就像您设置 assert x<函数开始时为0 ,函数中 x 小于0的任何地方都会引发异常吗?

  • Also, is there any way to set a business rule like if x < 0 raise error that is always checked without the try/except/finally so, if at anytime throughout the code x 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 x becomes less then 0 an exception is raised?

    推荐答案

    当整个函数中x小于零时,能够自动引发错误.您可以使用类描述符.这是一个示例:

    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):
        pass
    
    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 "my.py", line 7, in __set__
        raise LessThanZeroException('x is less than zero')
    LessThanZeroException: x is less than zero
    

    这篇关于使用断言的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆