如果您的库使用了错误的 Python 版本,应该引发什么适当的内置异常?
What's the appropriate built-in Exception to raise if your library is used with the wrong Python Version?
我有一个作为 .py 文件分发的简单库。如果从 Python 2 而不是 Python 3:
调用库,我想引发异常
def _check_version():
if sys.version_info < (3,):
raise _____Exception('This library depends on Python 3 strings. Please ensure you are using Python 3 instead of Python 2')
我应该引发什么内置异常? (我如何填写上面的空白?)在 builtin Exceptions 中我能找到的最接近的异常是 NotImplementedError。 DeprecationWarning 感觉很接近,但在这种情况下例外更合适。
为此我会使用 RuntimeError
;没有更具体的例外。
raise RuntimeError("<pkg> needs Python 3.7 or later")
- 这样 stderr 既可以提供信息又可以自动解析/记录
- 并明确指出罪魁祸首是
<pkg>
而不是其他软件包或 Python 本身,非 Python 用户;不得不编写供非 Python 用户使用的生产脚本。不要指望非 Python 用户阅读或理解 Python 回溯。
我有一个作为 .py 文件分发的简单库。如果从 Python 2 而不是 Python 3:
调用库,我想引发异常def _check_version():
if sys.version_info < (3,):
raise _____Exception('This library depends on Python 3 strings. Please ensure you are using Python 3 instead of Python 2')
我应该引发什么内置异常? (我如何填写上面的空白?)在 builtin Exceptions 中我能找到的最接近的异常是 NotImplementedError。 DeprecationWarning 感觉很接近,但在这种情况下例外更合适。
为此我会使用 RuntimeError
;没有更具体的例外。
raise RuntimeError("<pkg> needs Python 3.7 or later")
- 这样 stderr 既可以提供信息又可以自动解析/记录
- 并明确指出罪魁祸首是
<pkg>
而不是其他软件包或 Python 本身,非 Python 用户;不得不编写供非 Python 用户使用的生产脚本。不要指望非 Python 用户阅读或理解 Python 回溯。