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

Ben Finney ben+python at benfinney.id.au
Fri Jul 15 19:24:24 EDT 2011


Inside <fancheyujian at gmail.com> writes:

> I just follow some coding rules of me:
> 1. Controlling "input" strictly.

Asserting that the input is of a specific type is too strict. Does your
code work if the input is not a list or tuple?

I suspect strongly that the answer is yes, it works fine with any
sequence, even ones that don't inherit from ‘list’ nor ‘tuple’. It will
probably work with any sequence; it amy even work with any iterable.

Instead of insisting on specific types, you should support polymorphism:
expect *behaviour* and allow any input that exhibits that behaviour.

This is known as “duck typing”: you don't need to care whether it's a
duck, you just need to know whether it walks like a duck and quacks like
a duck. If it turns out to be a goose, but that won't affect your code,
you shouldn't care.

> 2. In a function keep doubting on its parameters until they're
> checked.

This is called “Look Before You Leap” (LBYL) programming, and is
generally considered not Pythonic.

Rather, “it is Easier to Ask Forgiveness than Permission” (EAFP) is the
Python programming style, and fits with its widespread reliance on
polymorphism (including “duck typing”).

Accept the input, and use it as though it has the correct behaviour –
without regard to what type is providing that behaviour.

If it doesn't have the expected behaviour, either the type will complain
(raising an exception that you can handle at an appropriate level in
your code), or your comprehensive unit tests will detect the
misbehaviour.

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.

> 3. Let potential errors raise as early as possible.

That is good practice. But you should not compromise polymorphism to
that.

-- 
 \            “The whole area of [treating source code as intellectual |
  `\    property] is almost assuring a customer that you are not going |
_o__)               to do any innovation in the future.” —Gary Barnett |
Ben Finney



More information about the Python-list mailing list