[Python-Dev] type categories -- an example

Andrew Koenig ark@research.att.com
19 Aug 2002 17:20:40 -0400


In the message that started all of this type-category discussion,
I said:

   As far as I know, there is no uniform method of determining into
   which category or categories a particular object falls.  Of course,
   there are non-uniform ways of doing so, but in general, those ways
   are, um, nonuniform.  Therefore, if you want to check whether an
   object is in one of these categories, you haven't necessarily
   learned much about how to check if it is in a different one of
   these categories.

As it happens, I'm presently working on a program in which I
would like to be able to determine whether a given value is:

        -- a member of a particular class hierarchy that I've defined;
        -- a callable object;
        -- a compiled regular expression; or
        -- anything else.

and do something different in each of these four cases.  Testing for
the first category is easy: I evaluate isinstance(x, B), where B is the
base class of my hierarchy.

Testing for the second is also easy: I evaluate callable(x).

How do I test for the third?  I guess I need to know the name of the
type of a compiled regular expression object.  Hmmm... A quick scan
through the documentation doesn't reveal it.  So I do an experiment:

        >>> import re
        >>> re.compile("foo")
        <_sre.SRE_Pattern object at 0x111018>

Hmmm... This doesn't look good -- Can I really count on a compiled
regular expression being an instance of _sre.SRE_Pattern for the
future?