isinstance(foo,bar) vs type(foo) is bar
if I'm checking what should ALWAYS BE A BASE OBJECT, what do I really lose from doing type is?
well, it's nice you give the full documented answer in your question, so your answer is you lose nothing! The only times where isinstance()
is necessary is when checking inheritance of a given class compared to another, as you well said and referenced. type()
shall be only used to check whether an instance is exactly of a given base type.
Other than the inheritance issue, you also lose the ability to test multiple types when using isinstance
. For example:
def chk(typ):
if not isinstance(typ, (str, int)):
raise ValueError('typ must be string or int')
...
The Python Docs for the built-in type function provide clear guidance on the difference between type (with one arg) and isinstance.
With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.class. The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.
To illustrate, take a look at the inheritance hierarchy below in module diamond:
Then take a look at the python console output below based on module diamond:
As per the documentation, it is more versatile and can cover a wider range of scenarios. With respect to the OP's original question - the performance characteristics were not stated as a valid reason to favour one over the other. Neither was readability.
For a more in-depth discussion, which includes an explanation on (in the words of the answerer) "why checking type equality is an even worse practice in recent Python versions than it already used to be", please see this highly voted answer