Checking if a variable is a dictionary
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sun Mar 9 10:23:25 EDT 2008
On Sun, 09 Mar 2008 06:58:15 -0700, Guillermo wrote:
> Okay, so I think I know where's the catch now -- you must rely on the
> fact that the protocol is implemented, there's no way to enforce it if
> you're expecting a parrot-like object. You'd try to call the speak()
> method and deal with the error if there's no such method?
That's right. That's called "duck typing" -- if all you want is something
that quacks like a duck, then it doesn't matter if it actually is a duck
or not.
Or if you prefer: if it quacks like a duck and swims like a duck, then
it's close enough to a duck as to make no difference.
Sometimes though, you need to check for a parrot up front. So I'd so this:
try:
something.speak
except AttributeError:
# No speak() method, so it can't be a parrot.
do_something_else()
else:
# It seems to follow the parrot protocol.
yummy_goodness = something.speak(5)
assert "spam" in yummy_goodness.lower()
--
Steven
More information about the Python-list
mailing list