Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 isinstance() vs type()
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.
my answer: whatever works for the particular situation.
"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

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 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

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
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.

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  isinstance() arg2 is limited to a type or a tuple of types Skaperen 5 389 Dec-02-2019, 06:07 PM
Last Post: Skaperen

Forum Jump:

Users browsing this thread: 1 Guest(s)