What's a simple utility function to differentiate between an old-style and a new-style python class or object

154 views Asked by At

What's a simple utility function to differentiate between an old-style and a new-style python class or object?

Are the following correct/complete:

isNewStyle1 = lambda o: isinstance(hasattr(o, '__class__') and o.__class__ or o, type)
isNewStyle2 = lambda o: hasattr(o, '__class__') and type(o) == o.__class__ or False

If not, then can you provide a solution. If so, is there a nicer way to do the check?

Using the above, I've not had any problems, but I don't have 100% confidence that it will work for all objects supplied as parameters.

2

There are 2 answers

3
John La Rooy On

Why not just

type(my_class) is type

True for new style classes, False for classic classes

You can support classes with different metaclasses like this (so long as the metaclass is subclassing type)

issublass(type(myclass), type)
0
Karmel On

How about:

class A: pass

class B(object): pass


def is_new(myclass):
    try: myclass.__class__.__class__
    except AttributeError: return False
    return True

>>> is_new(A)
False
>>> is_new(B)
True
>>> is_new(A())
False
>>> is_new(B())
True
>>> is_new(list())
True