Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to raise exception when function call is missing an argument in Python

If I have the function

def my_function(a,b,c):

and when the user calls the function, they omit the last argument

print(my_function(a,b))

what exception should I raise?

like image 712
Nicole Pineda Avatar asked Jun 20 '26 02:06

Nicole Pineda


2 Answers

As others have mentioned, Python will raise a TypeError if a function is called with an incorrect number of statically declared arguments. It seems there is no practical reason to override this behavior to raise your own custom error message since Python's:

TypeError: f() takes 2 positional arguments but 3 were given

is quite telling.

However, if you want to do this, and perhaps optionally allow a second argument, you can use *args.

def my_function(a, *args):
    b = None
    if len(args) > 1:
        raise TypeError("More than 2 arguments not allowed.")
    elif args:
        b = args[0]

    # do something with a and possibly b.

Edit: The other answer suggesting a default keyword argument is more appropriate given new additional details in OP’s comment.

like image 194
John B Avatar answered Jun 22 '26 16:06

John B


After discussion in the comment, it seems that what you want to do is catch an exception to pass a default argument if one was missing.

First of all, Python will already raise a TypeError if an argument is missing.

But you do not need to catch it to have default arguments since Python already provides a way to do this.

def my_function(a, b, c=0):
    pass

my_function(1, 2, 3) # This works fine
my_function(1, 2) # This works as well an used 0 as default argument for c
like image 35
Olivier Melançon Avatar answered Jun 22 '26 15:06

Olivier Melançon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!