In the specific case, type checks of "Pythonic" need not be checked. If there is no good reason, you must assume that the caller is passing a reasonable type (note: the "reasonable type" may be different from the "type you expect"), and make every effort to return something reasonable. If the caller switches to a type that is not reasonable, it is perfectly acceptable to allow them to deal with the consequences.
For example, someone might intelligently pass a Decimal number iterator to your square function:
>>> from decimal import Decimal >>> square(Decimal(line.strip()) for line in open("numbers.txt") [Decimal("4.0"), Decimal("9.0"), ...]
And everything will work! But explicit type checking will make this use case more complicated.
And then, for example, if someone passes something that is unreasonable, they can handle the error:
>>> square(42) … TypeError: 'int' object isn't iterable
This error message also (in the script) contains all the file names and line numbers needed to debug the problem.
On the other hand, it is sometimes useful to explicitly check the arguments when the caller may make a mistake with unexpected consequences. For example, if you write a function that will demonstrate very poor performance with list because it expects deque , then checking for if not isinstance(input, deque): raise TypeError("a deque must be used!") Can be justified .
The name of this "type processing method" is called Duck Typing .
source share