Is there a consensus on how to check a polymorphic instance?

Mike Meng meng.yan at gmail.com
Mon Nov 22 22:31:00 EST 2004


hi all,
I'm a newbie Python programmer with a C++ brain inside. I have a
lightweight framework in which I design a base class and expect user to
extend. In other part of the framework, I heavily use the instance of
this base class (or its children class). How can I ensure the instance
IS-A base  class instance, since Python is a fully dynamic typing
language?

I searched and found several different ways to do this:

1. In `Text Processing in Python', David Mertz suggests using `hasattr'
to check abilities instead of type checking.

2. In ActiveState's Python Cookbook site, Alex Martelli suggested a
safe and accurate `look before you leap' technique on
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52291

3. In this group, some others suggest using isinstance() builtin
function to check instance.

Now my questions:
1. Is my design speaks native Pythonish? Such design is native in C++
and Java OO style, but I'm not sure about this in Python.

2. As I state in title, is there a consensus on how to check a
polymorphic instance? I find all the three ways above is a little bit
tedious compared with C++ and Java, in which compile-time type checking
ensures the interface protocol, any better ideas in Python?
Any comments will be appreciated.




More information about the Python-list mailing list