What exception to raise if wrong number of arguments passed in to **kwargs?
Why not just do what python does?
>>> abs(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (3 given)
Remember that you can subclass Python's built-in exception classes (and TypeError
would surely be the right built-in exception class to raise here -- that's what Python raises if the number of arguments does not match the signature, in normal cases without *a
or **k
forms in the signature). I like having every package define its own class Error(Exception)
, and then specific exceptions as needed can multiply inherit as appropriate, e.g.:
class WrongNumberOfArguments(thispackage.Error, TypeError):
Then, I'd raise WrongNumberOfArguments
when I detect such a problem situation.
This way, any caller who's aware of this package can catch thispackage.Error
, if they need to deal with any error specific to the package, while other callers (presumably up higher in the call chain) call still catch the more generic TypeError
to deal with any errors such as "wrong number of arguments used in a function call".