Python:需要 kwarg,要引发哪个异常?

标签 python exception

确保使用特定 kwarg 调用方法的一种方法是:

def mymethod(self, *args, **kwargs):
    assert "required_field" in kwargs

引发 AssertionError 似乎不是最合适的做法。是否有一致同意的内置异常来处理此问题并提供很好的错误消息?

更多信息:存在需要传递 *args 和 **kwargs kinda' 的第 3 方子类化问题,因此将“required_field”作为位置参数并不是一个好的选择。

最佳答案

>>> def foo(bar): pass
... 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required positional argument: 'bar'

我会选择 TypeError..

关于Python:需要 kwarg,要引发哪个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13422601/

相关文章:

python - 使用 np.where 计算后如何保留 DataFrame/列和索引名称?

Python 无法正确排序 Unicode

c++ - 调用 MiniDumpWriteDump() 以捕获崩溃的最佳位置

python - 依赖于 Python 的并行任务处理并发,例如 GNU Make

python - 如何计算数据框中一行的增加/减少数量

c# - 何时使用 InvalidOperationException 或 NotSupportedException?

Delphi TPair 异常

sql - H2中通过PreparedStatement查询抛出异常: This method is not allowed for a prepared statement; use a regular statement instead

python - 使用 Python 通过 SSL/TLS 协议(protocol)上传文件

c++ - 异常和 std::list 类