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

139 views Asked by At

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?

3

There are 3 answers

3
Tom Karzes On BEST ANSWER

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.

1
Kai ZHAO On

This might work for you.

if len(args) + len(kwargs) > 3:
    raise RuntimeError('Error message')
0
Physmatik On

Expounding on the other answer: args is literally a tuple, kwargs is literally a dictionary. len isn't the only thing you can with them.

def foo(*args, **kwargs):
    print(args)
    print(kwargs)
    
foo(1, 'a', True, hello='world', sun='shines')

Result:

(1, 'a', True)
{'hello': 'world', 'sun': 'shines'}