Search code examples
pythonpython-3.xexceptionerror-handlingtry-catch

Python - Wrong number of arguments exception?


So I have a function like:

def my_code(arg1, *args):
    ....

And I want this function to only be able to take either 2 or 3 arguments (that means *args can only be 1 or 2 arguments). How do I throw an error message if the number of arguments is wrong? If I use a try/exception, is there a specific exception type for this?


Solution

  • You can get the length of args with len as you would for any tuple.

    def my_code(arg1, *args):
        if not 0 < len(args) < 3:
            raise TypeError('my_code() takes either 2 or 3 arguments ({} given)'
                            .format(len(args) + 1))
    
    my_code(1) # TypeError: my_code() takes either 2 or 3 arguments (1 given)
    my_code(1, 2) # pass
    my_code(1, 2, 3) # pass
    my_code(1, 2, 3, 4) # TypeError: my_code() takes either 2 or 3 arguments (4 given)