Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instance(object, type) returns True, should it not be False?

Tags:

python

I thought in Python that:

  • All classes ultimately are subclasses of object

  • All classes utimately are instances of type

  • object is an instance of type,
  • and type is a subclass of object.

However after checking isinstance(object,type) which returned True as expected. As object is an instance of type.

However I'm not sure why isinstance(type,object) returns True. (I thought this would be False as type isn't an instance of object).
Particularly as isinstance(type,type) is True ie it's an instance of itself.

And also issubclass(object,type) returns False, which was expected, but the results above isinstance(type,object) made me doubt wether I understood the relationships properly.

is it because isinstance works across subclasses but type doesn't?

like image 323
Yunti Avatar asked Sep 02 '25 10:09

Yunti


1 Answers

is it because isinstance works across subclasses but type doesn't?

Exactly. type(x) gives you the actual type of x, whereas isinstance(x, t) checks whether the type of x is t or a subclass of t. Hence, isinstance(x, t) is True even when type(x) == t would not.

In particular, object is the base class from which all other classes inherit, thus type, i.e. type(type), is also a subclass of object and isinstance(type, object) is true.

like image 75
tobias_k Avatar answered Sep 13 '25 01:09

tobias_k