duck-type-checking?

Matimus mccredie at gmail.com
Wed Nov 12 12:37:16 EST 2008


On Nov 12, 7:06 am, Joe Strout <j... at strout.net> wrote:
> Let me preface this by saying that I think I "get" the concept of duck-
> typing.
>
> However, I still want to sprinkle my code with assertions that, for  
> example, my parameters are what they're supposed to be -- too often I  
> mistakenly pass in something I didn't intend, and when that happens, I  
> want the code to fail as early as possible, so I have the shortest  
> possible path to track down the real bug.  Also, a sufficiently clever  
> IDE could use my assertions to know the type of my identifiers, and so  
> support me better with autocompletion and method tips.
>
> So I need functions to assert that a given identifier quacks like a  
> string, or a number, or a sequence, or a mutable sequence, or a  
> certain class, or so on.  (On the class check: I know about  
> isinstance, but that's contrary to duck-typing -- what I would want  
> that check to do instead is verify that whatever object I have, it has  
> the same public (non-underscore) methods as the class I'm claiming.)
>
> Are there any standard methods or idioms for doing that?
>
> Thanks,
> - Joe

The only thing that comes to mind is to use explicit checking
(isinstance). The new 'abc' module in 2.6 is worth a look. It seems
like this sort of thing might become a _little_ more popular.

I think duck-typing is great, but there are instances where you really
want the code to be better at documenting your intention about what
interface you expect an object to have, and also to catch the problems
that it might cause early and in a place where you might actually be
able to catch a meaningful exception. I've been looking and haven't
found any clear rules here. It is a trade off. The more complex the
interface, the more you will likely want to do an explicit check. On
the other hand, the more complex the interface the more likely it is
that you are violating the 'Interface Segregation Principle'. That is,
you probably want to consider breaking the functionality down into
smaller interfaces, or even separate classes.

IMO explicit checking, like global variables or using a 'goto' in C,
are evil. That isn't to say that you should _never_ use them. Heck,
there are plenty of gotos in CPython. You want to minimize, and
clearly document the places where your code is evil. There are times
where it is necessary.

Matt



More information about the Python-list mailing list