Explain Codes LogoExplain Codes Logo

How to find out if a Python object is a string?

python
type-checking
duck-typing
python-3
Anton ShumikhinbyAnton Shumikhin·Aug 27, 2024
TLDR

For lightning-fast string validation, unleash the power of isinstance(). Here's a fun tip: for a variable my_var just do:

is_string = isinstance(my_var, str)

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:

class CustomString(str): # Sort of like "premium" string, but fancier pass custom_str = CustomString("Yes, I'm a string too!") # isinstance() recognizes the noble bloodline print(isinstance(custom_str, str)) # Outputs: True

But hang on a minute! type() gets a little fussy with subclasses, as it checks for strict equality in type:

# Sorry, custom_str. type() says you're not a real string print(type(custom_str) is str) # Outputs: False

Python 2 vs Python 3

Coding for Python 2? Alright, grandpa! basestring is your friend:

# Python 2 style is_string = isinstance(my_var, basestring)

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:

from six import string_types is_string = isinstance(my_var, string_types)

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:

try: is_string_like = hasattr(my_var, "split") and callable(my_var.split) except AttributeError: is_string_like = False

Leveraging the 'six' library

Riding six library's wave ensures your code speaks both Python 2 and Python 3:

from six import string_types is_string = isinstance(my_var, string_types)

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:

2to3 -w my_entire_code_that_was_written_in_ancient_times.py

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.