Is there a consensus on how to check a polymorphic instance?
Dan Sommers
me at privacy.net
Wed Nov 24 06:48:56 EST 2004
On 23 Nov 2004 19:58:31 -0800,
"Mike Meng" <meng.yan at gmail.com> wrote:
First off, I have only been following this thread on and off, so if I'm
repeating things, I apologize.
> It seems to me the virtue of dynamic langauge is, if it looks like a
> cat, it's a cat ...
Google for "duck typing."
> ... But the problem is still there: how do you know what it looks like
> before you treat it as a cat? isinstance(), , as Steve state, is too
> rigid.
You don't.
Python also takes a "we're all adults here" philosophy. If your API
specifies "cat," and I pass your function an "InterfaceAdapter," it's
*my* problem.
If you're truly paranoid, make sure that your arguments at least have
the methods you're going to use:
# write 'foo' to the file-like object x; don't bother if x is not
# sufficiently file-like
def f( x ):
try: x.write
except AttributeError:
pass
else:
x.write( 'foo' )
# this works, too, but doesn't scale well (i.e., if 'foo' is some
# other non-trivial (maybe non-trusted) operation that can raise
# AttributeError):
def f( x ):
try: x.write( 'foo' )
except AttributeError:
pass
Regards,
Dan
--
Dan Sommers
<http://www.tombstonezero.net/dan/>
Never play leapfrog with a unicorn.
More information about the Python-list
mailing list