I don't think you would ever want to really do this - but I guess one hacky approach would be use getargspec()
from the inspect
module to determine the "names and default values of a Python function’s arguments.", and then wrap all function calls in try/except blocks.
>>> try:
func(2):
except TypeError as e:
print "Error! The function expected {} args".format(getargspec(func).args)
raise e
Error! The function expected ['integer', 'float'] args
Traceback (most recent call last):
File "<input>", line 5, in <module>
TypeError: func() takes exactly 2 arguments (1 given)
You could maybe wrap that into a custom exception too, which subclasses TypeError
(although here we are assuming that the TypeError
is being raised because the function wasn't passed the correct number of arguments which might be a bit of an over-simplification).
Note that you can't add code to do this inside the function object itself, as Python raises the TypeError
exception before it executes any of the code in the function body.
>>> def another_func(arg1):
print "Got inside the function - the arg was {}".format(arg1)
>>> another_func("hello")
Got inside the function - the arg was hello
>>> another_func()
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: another_function() takes exactly 1 argument (0 given)