Type checking versus polymorphism (was: list(), tuple() should not place at "Built-in functions" in documentation)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jul 16 04:47:38 CEST 2011


Ben Finney wrote:

[...snip explanation of duck-typing...]
> If you don't have comprehensive unit tests, that's where you should put
> your effort of strict interface testing. Not type assertions in the
> application code.

I agree with everything Ben said here, but he has missed something even more
fundamental.

Type *checking* breaks duck-typing. Type *assertions* are even worse,
because assertions aren't guaranteed to run. If you are using "assert
isinstance(...)" to validate input data, there are situations where your
validation step does not happen at all, and your code may just break in the
least convenient way. So not only are you validating the wrong way, but
sometimes you don't validate at all!

Assertions are for testing internal program logic, not for validation.

(I don't even like using assert for testing. How do you test your code with
assertions turned off if you use assert for testing?)



-- 
Steven




More information about the Python-list mailing list