I have to migrate a project from Python 2.7 to 3.7.
This line of code used to work in 2.7
if isinstance(obj, None):
for some reason it doesn't anymore. If I modify it this way:
if isinstance(obj, type(None)):
it will work though.
But my question is, what is the difference between this call:
isinstance(obj, None)
and
obj is None
why did the original devs decided to use isinstance over is? (in py 2.7)
Thanks.
CodePudding user response:
is
operator is used to check if both the objects are one and the same, whereas isinstance
is used to check if the second parameter appears anywhere in the inheritance chain of the first parameter.
obj is None
obj
is actually None
.
isinstance(obj, type(None))
Check obj
is None type object.
But actually there is only one object of None type. None is the only object of the None Type. So when you specify None type, you write it as type(None)
.
After all, isinstance(None, type(None))
is true.