Python Forum
testing value 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: testing value type (/thread-32141.html)



testing value type - Skaperen - Jan-23-2021

what is the reason we should do isinstance(foo,str) instead of type(foo) is str or type(foo) == str?


RE: testing value type - snippsat - Jan-23-2021

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.