Why does Python allow function calls with wrong number of arguments?

Python cannot know up-front what object you’ll end up calling, because being dynamic, you can swap out the function object. At any time. And each of these objects can have a different number of arguments.

Here is an extreme example:

import random

def foo(): pass
def bar(arg1): pass
def baz(arg1, arg2): pass

the_function = random.choice([foo, bar, baz])
print(the_function())

The above code has a 2 in 3 chance of raising an exception. But Python cannot know a-priori if that’ll be the case or not!

And I haven’t even started with dynamic module imports, dynamic function generation, other callable objects (any object with a __call__ method can be called), or catch-all arguments (*args and **kwargs).

But to make this extra clear, you state in your question:

It is not going to change while the program is running.

This is not the case, not in Python, once the module is loaded you can delete, add or replace any object in the module namespace, including function objects.

Leave a Comment