type() vs isinstance()mar. 03 mai 2016 by Rémi Duraffort
When running pylint on your Python source code, you might encounter this message:
Using type() instead of isinstance() for a typecheck. (unidiomatic-typecheck)
This message will be raised for this kind of code:
d = dict() if type(d) == dict: print("d is a dict")
The code is valid but pylint does prefer the use of isinstance(). Why is it preferable to use one instead of the other?
The short answer is: this code is unidiomatic. In fact, it does not make use of Duck typing.
In duck typing, an object's suitability is determined by the presence of certain methods and properties (with appropriate meaning), rather than the actual type of the object
In Python, it's preferable to use Duck Typing rather than inspecting the type of an object.
class User(object): def __init__(self, firstname): self.firstname = firstname @property def name(self): return self.firstname class Animal(object): pass class Fox(Animal): name = "Fox" class Bear(Animal): name = "Bear" # Use the .name attribute (or property) regardless of the type for a in [User("John"), Fox(), Bear()]: print(a.name)
The second reason not to use type() is the lack of support for inheritance.
class MyDict(dict): """A normal dict, that is always created with an "initial" key""" def __init__(self): self["initial"] = "some data" d = MyDict() type(d) == dict # False type(d) == MyDict # True d = dict() type(d) == dict # True type(d) == MyDict # False
The MyDict class has all the properties of a dict, without any new methods. It will behave exactly like a dictionary. But type() will not return the expected result.
Using isinstance() is preferable in this case because it will give the expected result:
d = Mydict() isinstance(d, MyDict) # True isinstance(d, dict) # True d = dict() isinstance(d, MyDict) # False isinstance(d, dict) # True
As a conclusion, try to avoid (as much as possible) the use of type or isinstance and prefer Duck Typing.
More information on StackOverflow