0

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Linden
  • 531
  • 3
  • 12
  • 1
    Does this answer your question? [How do you set a conditional in python based on datatypes?](https://stackoverflow.com/questions/14113187/how-do-you-set-a-conditional-in-python-based-on-datatypes) – MisterMiyagi Oct 20 '20 at 14:32
  • 2
    TLDR: ``def instance_but_not_subclass(obj, cls): return type(obj) is cls`` – MisterMiyagi Oct 20 '20 at 14:33

1 Answers1

1

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.

Xtrem532
  • 756
  • 8
  • 19