Pythonic 处理此错误情况
在下面的代码中,我使用 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__
In the code below, is my use of assert
justified? If anything is wrong, an error will occur anyway when I try to access the attributes. On the other hand, the assert provides a descriptive error message.
Do you think I should keep the assertion?
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__
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
assert
不是用于输入验证,而是用于查找您构建代码所依据的假设中的缺陷。它是一个调试和文档工具,但可以禁用。如果你想提供一个好的错误消息,raise TypeError("Object is not abound method")
- 这就是它的用途。assert
is not for input validation, it's for finding flaws in the assumptions you built your code on. It's a debugging and documentation tool, but it can be disabled. If you want to provide a good error message,raise TypeError("Object is not a bound method")
- that's what it's for.在我看来,这里的
assert
正在检查代码所做的假设。如果类使用不正确(即编程错误),它将失败。如果情况确实如此,那么恕我直言,这里使用
assert
是合理的。确实,当使用不正确时,Python 会慷慨地抛出异常,而 EAFP 是一个很好的策略。然而,有时解释器抛出的错误描述性不够,无法轻松定位问题,在这种情况下使用assert
是合适的。它还应该与适当的文档相结合,说明类期望如何使用(即传递的方法应该具有某些属性)。如果我误解了您的示例,并且您在此处使用
assert
来验证用户可能犯的错误,那么这不是一个好主意。It appears to me that the
assert
here is checking an assumption the code is making. It will fail if the class is used incorrectly (i.e. programming error).If this is indeed the case, then the use of
assert
here is IMHO justified. True, Python generously throws exceptions when things are used incorrectly, and EAFP is a good strategy. Yet, sometimes the errors thrown by the interpreter aren't descriptive enough to make it easy to locate the problem, and anassert
in such cases is appropriate. It should also be coupled with appropriate documentation that states how the class expects to be used (i.e. the passed method should have certain attributes).If I have misunderstood your sample and you're using the
assert
here to validate something the user could err with, then it's not a good idea.