I am looking for something in the following piece of code so that the isinstance() check afterwards evaluates to True in any case:
i = WonderfulClass()
classinfo_of_i = something(i)
isinstance(i, classinfo_of_i) # must evaluate to True
If type is your answer, I’d be grateful if you explained why. Is type the real counterpart of isinstance? Or, asked the other way round, can you think of a case where isinstance(i, type(i)) evaluates to False?
This question arose in the context of the simple way to check if the elements of a list or set are single type?, where we have to go through a sequence and check if all the sequence elements are of the same kind. In this context, elements will be compared to each other. This comparison could be based on type or based on isinstance.
Relevant documentation regarding isinstance(object, classinfo):
Return true if the object argument is an instance of the classinfo
argument
I can’t see any situation where
isinstance(i, type(i))would not returnTrue.type()inspects and returns the type object from an instance so there’s no reason why the returned value would fail theisinstance()check.Digging into the source of cPython, we see that the code behind
type()simply returns the type object attached to the instance:while the first thing that the isintance() code does is check if the types match exactly (it would later move on to match against classes in the chain of inheritance):
Note that
Py_TYPEis simply a macro that returnsobj->ob_typewhich matches the return value oftype(). This is defined in Include/object.h as: