new-style class instance check

John Roth newsgroups at jhrothjr.com
Mon Apr 12 07:57:38 EDT 2004


"Richard Gruet" <rjgruet at yahoo.com> wrote in message
news:c59uvd$fgh$1 at apollon.grec.isp.9tel.net...
> Hi all,
>
> How to determine that an object o is for sure an instance of a new-style
> class, without knowing of which specific class ?
> That is, if I define a function:
>
> def isNewStyleClassInstance(o):
>     pass    ## to be completed
>
> .. I want to pass the following test:
>
> def C: pass
> def CNew(object): pass
>
> assert not isNewStyleClassInstance(C()) # InstanceType
> assert isNewStyleClassInstance(CNew())
> assert not isNewStyleClassInstance(1)    # instance of type int
> # and naturally for all other types of o the function should return False.

The following untested code should work:

import types

def isNewStyleClass(obj):
    if type(obj) is types.InstanceType:
        if hasattr(obj.__class__, "__mro__"):
            return True
    return False



John Roth
>
> Richard
>
>





More information about the Python-list mailing list