pythonpython-2.xnew-style-class

How to check if object is instance of new-style user-defined class?


Code:

import types


class C(object):
    pass


c = C()
print(isinstance(c, types.InstanceType))

Output:

False

What correct way to check if object is instance of user-defined class for new-style classes?

UPD:

I want put additional emphasize on if checking if type of object is user-defined. According to docs:

types.InstanceType
The type of instances of user-defined classes.

UPD2:

Alright - not "correct" ways are OK too.

UPD3:

Also noticed that there is no type for set in module types


Solution

  • You can combine the x.__class__ check with the presence (or not) of either '__dict__' in dir(x) or hasattr(x, '__slots__'), as a hacky way to distinguish between both new/old-style class and user/builtin object.

    Actually, this exact same suggestions appears in https://stackoverflow.com/a/2654806/1832154

    def is_instance_userdefined_and_newclass(inst):
        cls = inst.__class__
        if hasattr(cls, '__class__'):
            return ('__dict__' in dir(cls) or hasattr(cls, '__slots__'))
        return False
    

    >>> class A: pass
    ... 
    >>> class B(object): pass
    ... 
    >>> a = A()
    >>> b = B()
    >>> is_instance_userdefined_and_newclass(1)
    False
    >>> is_instance_userdefined_and_newclass(a)
    False
    >>> is_instance_userdefined_and_newclass(b)
    True