Python Forum
isinstance() vs type() - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: isinstance() vs type() (/thread-21753.html)



isinstance() vs type() - Skaperen - Oct-12-2019

a while back, like 2 or 3 years ago, i read here that it was better to test types using the isinstance() function than using the type() function. i have been coding that way ever since. i'd like to know if this was just better coding practice or if there is an issue with the type() function. i've come upon a case where isinstance() adds complications while type() is simpler. i need to do a dictionary lookup based on the type of a variable. i want to be sure the type() function is really safe for this. is it?


RE: isinstance() vs type() - Larz60+ - Oct-13-2019

my answer: whatever works for the particular situation.


RE: isinstance() vs type() - perfringo - Oct-13-2019

"In the face of ambiguity, refuse the temptation to guess."

No knowledge of the meaning of 'safe'.

"better to test types using the isinstance()" is probably coming from Python type() documentation

Quote:The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.

There are situations where one doesn't need to check class but only check whether object has specific interface (duck-typing). This functionality is provided by built-in collections.abc

Quote:This module provides abstract base classes that can be used to test whether a class provides a particular interface; for example, whether it is hashable or whether it is a mapping.

Is value hashable to be used as dictionary key:

>>> from collections.abc import Hashable                                                  
>>> lst = ['abc', ['abc'], ('abc')]                                                       
>>> [isinstance(item, Hashable) for item in lst]                                          
[True, False, True]



RE: isinstance() vs type() - Gribouillis - Oct-13-2019

Skaperen Wrote:i'd like to know if this was just better coding practice or if there is an issue with the type() function.
I think it is a matter of abstraction level. Isinstance() is the abstract interface while type() is the "implementation detail". It means that code using isinstance() should be more robust than code using type(), and of course it takes subclasses into account. That said, I'd like to know more about your dictionary issue.