Check in Python if a value is instance of a custom class

I’m working on a object based serializer/deserializer in python and as a result I need to know if a value is instance of class or not. First, I realized that in contrary to Java, there is really no clean way of determining if variable is holding an instance of a class or a primitive type

For clarification: I know in java due to static typing it probably never happens to need to check this. But to a java programmer is intuitive to be able to check if a value is instance of object and to assume that all other value types such as arrays and primitives won’t be. (thanks to tea-drinker on reddit)

This is largely due to the fact all primitives are actually instance of the classes for those primitives. You can verify as shown below on Python 3x:

Therefore, checking “isinstance(val, object)” will return True pretty much for any value (At least to mu knowledge)!

You can see that type of a primitive value is the class for int values. Therefore, the intuitive ways that comes to the mind of at least someone who is more experienced in a language like Java don’t really work:

Finally it seemed like the only reasonable way is to check if the variable has either __dict__ or __slot__ attributes. These attribute are created when the __call__ method of the meta class is called (check this out for a great read)

This also works for class that define __slots__

Leave a reply:

Your email address will not be published.

Site Footer