Pythonic 处理此错误情况

标签 python error-handling assert

在下面的代码中,我使用 assert 是否合理?如果出现任何问题,当我尝试访问属性时无论如何都会发生错误。另一方面,断言提供了描述性错误消息。

你认为我应该保留这个断言吗?

class WeakBoundMethod:
    def __init__(self, meth):
        assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\
               'Object is not a bound method.'

        self._self = weakref.ref(meth.__self__)
        self._func = meth.__func__

最佳答案

assert不是用于输入验证,而是用于查找构建代码的假设中的缺陷。它是一个调试和文档工具,但可以禁用。如果您想提供良好的错误消息,请raise TypeError("Object is not abound method") - 这就是它的用途。

关于Pythonic 处理此错误情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7298412/

相关文章:

Python Pandas - 将多列合并为一列交错列

python - 无法为 Python 2.7 获取 SFML

python - 在 Python 中迭代列表头部的优雅方法

使用Scanner时出现Java异常错误

c# - WPF MVVM 应用程序中多个异步调用期间的单个错误弹出

python - 在 Python3/Numpy 中过滤数组并返回索引

ruby-on-rails - Rails Validation表单中的整洁错误

c++ - 如何使用可选的格式化消息实现符合标准的断言宏?

performance - 慢 Scala 断言

java - 具有多个接受答案的 JUnit 测试