duck-type-checking?

George Sakkis george.sakkis at gmail.com
Fri Nov 14 17:39:46 EST 2008


On Nov 14, 4:49 pm, Joe Strout <j... at strout.net> wrote:

> So things like this should suffice:
>
>         # simple element
>         assert(is_stringlike(foo))
>         assert(is_numeric(foo))
>         assert(is_like(foo, Duck))
>
>         # sequence of elements
>         assert(seqof_stringlike(foo))
>         assert(seqof_numeric(foo))
>         assert(seqof_like(foo, Duck))
>         # (also "listof_" variants for asserting mutable sequence of whatever)
>
>         # dictionary of elements
>         assert(dictof_like(foo, str, int))
>
> Hmm, I was already forced to change my approach by the time I got to  
> checking dictionaries.  Perhaps a better formalism would be a "like"  
> method that takes an argument, and something that indicates the  
> desired type.  This could be a tree if you want to check deeper into a  
> container.  Maybe something like:
>
>         assert(fits(foo, dictlike(strlike, seqlike(intlike))))
>
> which asserts that foo is something dictionary-like that maps string-
> like things to something like a sequence of integer-like things.  Most  
> cases would not be this complex, of course, but would be closer to
>
>         assert(fits(foo, strlike))
>
> But this is still pretty ugly.  Hmm.  Maybe I'd better wait for  
> ABCs.  :)

You might also be interested in the typecheck module whose syntax
looks nicer, at least for the common cases: http://oakwinter.com/code/typecheck/dev/

George



More information about the Python-list mailing list