TomNash
TomNash

Reputation: 3288

How to differentiate between unexpected keyword argument and missing positional argument TypeError

If I have a function below, how can I differentiate between these two 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'

I'd like to do something like psuedocode

try:
    test_method()
except TypeError(MissingPositionalArgument):
    do_something()
except TypeError(UnexpectedKeywordArgument):
    do_something_else()

Upvotes: 1

Views: 68

Answers (1)

John Gordon
John Gordon

Reputation: 33335

You can inspect the text of the exception message:

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

Upvotes: 1

Related Questions