2

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?

12
  • 5
    Do you want to raise an exception or catch it? Because Python already raises a TypeError for you in that case. Commented Mar 24, 2018 at 5:16
  • I have a default argument for c that the function should use if the user omits the last argument when calling. I need to raise an exception in the case that the user omits the argument, so the function uses my default argument. Commented Mar 24, 2018 at 5:23
  • 2
    So what you want to do is use a default argument instead of raising an exception? You meant 'what exception should I catch'? Commented Mar 24, 2018 at 5:24
  • 1
    The function will use the default argument, you don't need to raise an exception. Commented Mar 24, 2018 at 5:24
  • 1
    Please provide an example to illustrate what you are envisioning inside the function here. Commented Mar 24, 2018 at 5:34

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.