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:
1 2 |
>>> type(1) <class 'int'> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
>>> class Test1(): def __init__(self,x): self._x = x def get_x(self): return self._x x = property(get_x) >>> t1= Test1(1) # using isinstance >>> isinstance(t1,object) True >>> isinstance(1,object) True # checking class attribute >>> hasattr(t1,'__class__') True >>> hasattr(1,'__class__') True |
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)
1 2 3 4 |
>>> hasattr(t1,'__dict__') or hasattr(t1,'__slots__') True >>> hasattr(1,'__dict__') or hasattr(1,'__slots__') False |
This also works for class that define __slots__