Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
testing value type
#1
what is the reason we should do isinstance(foo,str) instead of type(foo) is str or type(foo) == str?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
This sum it up fine.
type() vs. isinstance()
Quote:Conclusions
isinstance is usually the preferred way to compare types.
It’s not only faster but also considers inheritance, which is often the desired behavior.
In Python, you usually want to check if a given object behaves like a string or a list, not necessarily if it’s exactly a string.
So instead of checking for string and all it’s custom subclasses, you can just use isinstance.

On the other hand, when you want to explicitly check that a given variable is of a specific type (and not its subclass) - use type.
And when you use it, use it like this: type(var) is some_type not like this: type(var) == some_type.

And before you start checking types of your variables everywhere throughout your code, check out why “Asking for Forgiveness” might be a better way.
buran and Skaperen like this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  testing value type 2 Skaperen 2 1,876 Jan-24-2021, 08:44 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020