python - 如何区分意外的关键字参数和缺少的位置参数 TypeError
问题描述
如果我有下面的功能,我该如何区分这两者TypeError
?
def test_method(a):
print(a)
test_method(a=1) # 'a'
test_method() # TypeError: test_method() missing 1 required positional argument: 'a'
test_method(a=1, b=2) # TypeError: test_method() got an unexpected keyword argument 'b'
我想做一些类似伪代码的事情
try:
test_method()
except TypeError(MissingPositionalArgument):
do_something()
except TypeError(UnexpectedKeywordArgument):
do_something_else()
解决方案
您可以检查异常消息的文本:
try:
some_function()
except TypeError as ex:
if 'some text' in str(ex):
# handle it...
elif 'some other text' in str(ex):
# handle it...
推荐阅读
- flutter - MissingPluginException - HttpClient 的权限问题
- kubernetes - Kubernetes 升级计划命令失败,因为 etcd 集群无法使用维护客户端拨打端点 https://192.168.5.12:2379
- app-store-connect - 如何获取安装应用程序的设备数量?
- javascript - 我想了解为什么我作为道具传递给 React 功能组件的数据显示为未定义?
- javascript - PyCharm 中的“事件”字样
- dataset - 如何从 kaggle 中读取无 CSV 数据集?
- keras - 无法识别导致错误的图像 - PIL.UnidentifiedImageError:无法识别图像文件
- python - 计算单元格 j 和单元格 j+1 之间的差异,然后计算数据帧的 j+1 和 j+2、j+2 和 j+3...,并保持挖掘机结果(关闭))
- 6502 - 使用 .align 时 CL65 不调整地址
- vue.js - Vue v-model绑定到父组件输入元素不起作用