Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exception to raise if wrong number of arguments passed in to **kwargs?

Suppose in python you have a routine that accepts three named parameters (as **kwargs), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would you raise? RuntimeError, a specifically created exception, or other?

like image 553
Stefano Borini Avatar asked Dec 26 '09 19:12

Stefano Borini


2 Answers

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".

like image 135
Alex Martelli Avatar answered Oct 22 '22 18:10

Alex Martelli


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)
like image 30
Dustin Avatar answered Oct 22 '22 18:10

Dustin