How to determine if a variable is an instance in Python 3? I consider something to be an instance if it has __dict__
attribute.
Example:
is_instance_of_any_class(5) # should return False
is_instance_of_any_class([2, 3]) # should return False
class A:
pass
a = A()
is_instance_of_any_class(a) # should return True
I have seen messages about using isinstance(x, type)
or inspect.isclass(x)
but this would give True for the class (A), not the instance.
I think your understanding of what an instance is wrong here, since everything is an object in python, so 5
is an object of class int
and [2,3]
is an object of class list
and so on.
isinstance(x, y)
is the way to go if you just want to check if x
is an object of y
, but if you want to check if x
is an object of builtin class or your own custom defined class then you should be checking the existence of __dict__
using hasattr(x, '__dict__')
.