Checking if a variable is a dictionary

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Mar 10 04:59:37 EDT 2008


Guillermo a écrit :
> Mamma mia! My head just exploded. I've seen the light.
> 
> So you only need to ·want· to have a protocol? That's amazing... Far
> beyond the claim that Python is easy. You define protocols in writing
> basically! Even my grandma could have her own Python protocol.
> 
> Okay, so I think I know where's the catch now -- you must rely on the
> fact that the protocol is implemented,

Indeed. But even with static declarative typing à la Java, you must rely 
on the fact that the protocol is *correctly* implemented (what about 
having file.close sending mails to all your contacts and then rebooting 
the computer ?-). IOW, at some point, you have to trust the coder anyway.

> there's no way to enforce it if
> you're expecting a parrot-like object.

Yes there is:

> You'd try to call the speak()
> method 

That's it.

> and deal with the error if there's no such method?

Either catch the AttributeError and raise a TypeError or ValueError (or 
some more specific one) instead, or just let the AttributeError 
propagate - whichever makes more sens given the context. I'd say the 
default would be to catch the AttributeError and raise a TypeError 
instead (that's at least what len() does when passed an unsized object).





More information about the Python-list mailing list