[Python-3000] my take on "typeclasses"
Baptiste Carvello
baptiste13 at altern.org
Wed May 10 01:22:34 CEST 2006
Oleg Broytmann a écrit :
> On Tue, May 09, 2006 at 10:31:02PM +0200, tomer filiba wrote:
>
>>i.e., "is the object addable?" == "hasattr(obj, '__add__')".
>
>
> Even this is meaningless: '1'+1. So duck typing is:
>
> try:
> return a+b
> except TypeError:
> return "Oops..."
>
>
Well, while only the second example is true duck typing, the first one also is
some sort of duck-typing, with a weaker promise:
"if it looks like a duck from half a mile away, then it *might* be a duck"
Sometimes, you just don't want to walk half a mile for nothing :)
Less metaphorically, the "just do it" test for an assumption can have
side-effects. You might want some information on the status of the assumption
*before* you can afford the side-effects. So you want a test with the following
promise:
"every test that could be done now (without side-effects) has been tried, and
the assumption has still not been proven false".
Of course, this does not prove the assumption true, but it provides a well
defined and possibly useful piece of knowledge. False positives can still be
caught later on by true duck typing.
Of course this is only useful if you really need the early warning. I can think
of 2 use cases:
1) in interactive use, having the exception close to the code responsible for
the problem avoids confusing the user. This is the case of using callable() on a
candidate callback. This does not catch every problem, but still provides a
better user experience in the common cases where it does. And if the test has no
false negatives, it has *no cost* at all.
2) in numerical calculations, you might want to do as many tests as possible
before attempting a time-costly operation.
Sorry for this "philosophical" post. I hope it helps clarify the current
discussion about what is really duck typing.
Baptiste
More information about the Python-3000
mailing list