pythonexceptionargumentskeyword-argument

How can I raise an Exception if more than three arguments are passed into a function, function is called with *args, **kwargs?


So I have the following function:

def run_task(*args, **kwargs):
    jobserve_task_name = args[0]
    parser_code, group_name, real_execution_intdate = _extract_celery_task_args(*args, **kwargs)

And I want to raise an exception just above the last line, where if the total number of *args, **kwargs is greater than 3.

Is there a way to do this?


Solution

  • This should do what you want:

    if len(args) + len(kwargs) > 3:
        raise TypeError("too many arguments")
    

    I used TypeError since that's the same exception you get if you pass too many arguments to a function with fixed arguments.