1

I'm trying to figure out how the comparison type(v) == int works in Python (and why should I use is instead of == in this case), for what I've been reading about classes and metaclasses in Python, but still I don't know exactly what happens (what is being compare exactly) when you compare two classes (classes themselves, not instances). I supposed that the answer would be in the definition of the equals method of the type metaclass, which is the class of int and type(v), so I would like to see the source code of that definition but I haven't been able to find it yet.

So, please, could anybody point me to the exact definition of the method or explain to me what is happening under the hood when I compare two classes (two instances of the type metaclass/class)?

rmoret
  • 133
  • 2
  • 10
  • 2
    Classes are objects, just like class instances. `3` is an instance of the `int` class. `int` is an instance of class `type`. They can be compared just like any other object. – Tim Roberts Nov 14 '22 at 22:10
  • 3
    Classes inherit their `__eq__` implemention from `object` I'm pretty sure, which does equality by identity. Using `is` to compare is more of a convention than a necessity – juanpa.arrivillaga Nov 14 '22 at 22:10
  • And missing in your comments: actually unless one has a very specific need, class comparison should always be done through calling `isinstance` (for instances) and `issubclass` for classes: these correctly take into account subclassing (d'oh) and can route the comparison by hooks that allow virtual subclassing. – jsbueno Nov 15 '22 at 13:45

0 Answers0