NikoX
NikoX

Reputation: 127

Differ between type errors

I have a function say:

def foo(a, b, c):
  ...

I can handle TypeError due to missing arguments like:

try:
  foo(1, 2)
except TypeError:
  print("Arguments are not ok.")

The type error can be raised for many reasons like:

The problem here is that I want to know if the error was raised because of less arguments provided or too many arguments provided.

Yes, I can check what the error message says using if statements but that seems kind of inefficient. Is there a better way and probably efficient of doing this?

Upvotes: 0

Views: 52

Answers (3)

NikoX
NikoX

Reputation: 127

I was able to get a workaround for this:

import inspect

def foo(x, y, z):
   ...

args = (1, 2)
try:
  foo(*args)
except TypeError:
  fooargs = inspect.getfullargspec(foo).args

  if len(fooargs) > len(args):
    print('Less arguments passed')

  elif len(fooargs) < len(args):
    print('Too many arguments passed')

Upvotes: 1

Bhagyesh Dudhediya
Bhagyesh Dudhediya

Reputation: 1856

Not sure what is the intention behind this as Exception handling gives the clear reason for failure. But still if you need to do it then here is what might work for you:

try:
    # Call to the function
except TypeError as ex:
    if (re.search(r"missing.*positional argument", str(ex))):
        print ("Less no. of arguments passed")
    elif (re.search(r".*takes\s*\d+.*but.*were given", str(ex))):
        print ("Too many arguments passed")
    else:
        print ("Another error")

Upvotes: 0

Talon
Talon

Reputation: 1884

You could give each argument a default value and check for that, and also add a catchall

def foo(a=None, b=None, c=None, *_too_much):
    if a == None:
        pass  # argument-checks here
    ...
    if _too_much:
        pass  # Too many arguments handling here

Though, what is your use-case for this? More verbose handling of usage errors for interactive use or something else? If your user is not specifically using this in a REPL or something, there's probably a better way of doing what you want.

Upvotes: 0

Related Questions