-2

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.

Damian
  • 178
  • 11
  • 9
    Since everything is an object, everything is an instance of *something*… What's the use case? Please ensure you don't have an [XY Problem](http://xyproblem.info). – deceze Mar 14 '19 at 12:52
  • 3
    *"I consider something to be an instance if it has `__dict__` attribute."* – Sooo… `hasattr(o, '__dict__')`…? – deceze Mar 14 '19 at 12:54
  • 1
    Yeah, i think checking for `__dict__` is better – han solo Mar 14 '19 at 12:55
  • 1
    Not just better, but it's exactly what the OP wants. All the talk about detecting "instances" is a red herring, because everything *is* an instance, whether or not it has a `__dict__` attribute. – chepner Mar 14 '19 at 12:57
  • 1
    I think OP's understanding of what is an _instance_ is wrong, 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 `__dict__`. – Rohit Mar 14 '19 at 13:23

1 Answers1

2

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__').

Rohit
  • 3,659
  • 3
  • 35
  • 57