简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM