首页 > 解决方案 > 如何区分意外的关键字参数和缺少的位置参数 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()

标签: pythonpython-3.x

解决方案


您可以检查异常消息的文本:

try:
    some_function()
except TypeError as ex:
    if 'some text' in str(ex):
        # handle it...
    elif 'some other text' in str(ex):
        # handle it...

推荐阅读