0

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.

khosrow
  • 8,799
  • 4
  • 21
  • 24
  • `isNewStyle = lambda x: hasattr(x, "__weakref__")` Just pick a feature that new style classes have, but old style classes don't. – Joel Cornett May 24 '12 at 03:24

2 Answers2

1

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
Karmel
  • 3,452
  • 2
  • 18
  • 11
0

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)
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • That only covers classes, I'm trying to account for any object, for example type(list()) is list, so that would fail your test. – khosrow May 24 '12 at 03:04
  • Then my_class = type(list()). Just do that test for the type of any arbitrary object. – Andrew Gorcester May 24 '12 at 03:09
  • @Cyrus, Magically trying to support instances and classes is a bad idea. Consider that a class _is_ an _instance_ of `type` (usually). – John La Rooy May 24 '12 at 03:10