Should I check the types of constructor arguments (and at other places too)?

Xolve picture Xolve · Mar 2, 2009 · Viewed 9.8k times · Source

Python discourages checking the types. But in many cases this may be useful:

  1. Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later.

  2. Checking functions arguments.

  3. In properties. If someone sets a wrong value or different type, I should respond quickly.

Answer

batbrat picture batbrat · Mar 2, 2009

The simple answer is No, use Polymorphism, Exceptions etc.

  1. In the case of constructor arguments being of the wrong type, an exception will be thrown when executing code that depend s on the parameter being of a particular type. If it is a weird, domain specific thing, raise your own Exception. Surround blocks of code which are likely to fail with try-except and handle errors. So it is better to use Exception handling. (Same goes for function arguments)

  2. In properties, the same argument applies. If you are validating the value received, use an assertion to check its range etc. If the value is of the wrong type, it will fail anyway. Then, handle AssertionError.

In Python, you treat programmers as intelligent beings!! Just document your code well (make things obvious), raise Exceptions where appropriate, write polymorphic code etc. Leave the Exception handling(where it is appropriate only)/errors in construction to the client code.

Warning
Leaving Exception handling to clients doesn't mean that you should chuck a lot of garbage errors at the unwitting user. If at all possible, handle exceptions that might occur due to bad construction or any other reason in your code itself. Your code should be robust. Where it is impossible for you to handle the error, politely inform the user/client code programmer!

Note
In general, bad arguments to a constructor isn't something I worry about too much.