Skip to content
Advertisement

Check if an item is an instance but not a subclass

How can you check if an object is an instance of a class but not any of its subclasses (without knowing the names of the subclasses)? So if I had the below code:

def instance_but_not_subclass(object, class):
    #code
    return result

class item(object):
    
class item_2(item):

...

class item_n(item): 

a = item()
b = item_2()
...
c = item_n()

instance_but_not_subclass(a, item)
instance_but_not_subclass(b, item)
...
instance_but_not_subclass(c, item)

what would go in the #code space that would produce the output?:

True
False
...
False

Because issubclass() and isinstance() always return True.

Advertisement

Answer

The object.__class__ attribute is a reference to the exact class of an object, so you only need to compare that with your argument

def instance_but_not_subclass(obj, klass):
    return obj.__class__ is klass

Don’t name variables class, its a keyword and won’t work, use klassor typ instead. Also, the variable name object shadows the build in object, so use something like obj.


I personally like the .__class__ variant more, but the more “pythonic” variant would probably be

def instance_but_not_subclass(object, klass):
    return type(obj) is klass

because it doesn’t access any dunder (__) attributes.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement