Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 isinstance() vs type()
#1
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?
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote
#2
my answer: whatever works for the particular situation.
Quote
#3
"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]
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Life of Brian: Conjugate the verb, "to go" !
Quote
#4
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.
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)