How to find out if a Python object is a string?
For lightning-fast string validation, unleash the power of isinstance()
. Here's a fun tip: for a variable my_var
just do:
True
means my_var
is saying "Slim Shady", AKA a string, and False
means it's got an identity crisis.
Understanding isinstance() and string checks
When you need to confirm if a variable is batting for team str
, isinstance()
is your guy. What makes isinstance()
the MVP of this game is how it embraces subclasses. Let's say you've got your own string type:
But hang on a minute! type()
gets a little fussy with subclasses, as it checks for strict equality in type:
Python 2 vs Python 3
Coding for Python 2? Alright, grandpa! basestring
is your friend:
But wake up, it's 2022 and Python 2 isn't the cool kid anymore. For string checks in Python 3, team up with str
. Writing code for this vast timeline? Rope in six
library:
What's the plan B for string identification?
Say hello to Duck typing
Sometimes, what someone does matters more than who they are. Duck typing puts behaviour over type:
Leveraging the 'six' library
Riding six
library's wave ensures your code speaks both Python 2 and Python 3:
Meet the Python whisperer: 2to3
Better late than never! If you're transitioning from Python 2 to 3, 2to3
will change all those outdated basestring
to hip str
:
What matters when you type-check?
Python's dynamism
Python loves to keep you on your toes with its dynamic type system. isinstance()
deftly handles this whirlwind and checks an object's type at runtime, but don't let it get to your head! Overusing type checking is like ordering a pizza on treadmill.
Python 3 already took the Unicode pill
In Python 3, the line between strings and unicode strings has been erased—they're both str
. This makes your life easier, trust us.
Python Glossary to the rescue
Do yourself a favor, bookmark the Python Glossary. It's your cheat sheet for Python's best practices.
The perfect scenarios to ditch isinstance()
Sometimes, it's not about who you are, but how you behave. In scenarios where an object's behavior is important than its type, forget isinstance()
and dance to the tune of duck typing.
Was this article helpful?