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:

JavaScript

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

JavaScript

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

JavaScript

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

JavaScript

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

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