NotImplemented 不是异常¶
ID: py/raise-not-implemented
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- reliability
- maintainability
Query suites:
- python-security-and-quality.qls
NotImplemented 不是异常,但经常被错误地用作 NotImplementedError 的替代品。执行 raise NotImplemented 或 raise NotImplemented() 会引发 TypeError。当 raise NotImplemented 用于标记实际上永远不会调用的代码时,这个错误是良性的。但是,如果它被调用,那么将引发 TypeError 而不是预期的 NotImplemented,这可能会使调试问题变得困难。
NotImplemented 的正确用法是实现二元运算符。不打算调用的代码应该引发 NotImplementedError。
建议¶
将 NotImplemented 的用法替换为 NotImplementedError。
示例¶
在下面的示例中,方法 wrong 在被调用时会错误地引发 TypeError。方法 right 会引发 NotImplementedError。
class Abstract(object):
def wrong(self):
# Will raise a TypeError
raise NotImplemented()
def right(self):
raise NotImplementedError()
参考¶
Python 语言参考:NotImplementedError 异常.
Python 语言参考:模拟数值类型.