Text vs str, when using python type hints
What is the difference between Text and str in Python type hints? How should you decide which one to use when annotating string-related variables in your code?
When using type hints in Python, you might come across both str and Text. At first glance, they may seem similar because they both represent string-like types—but there are subtle differences, especially when considering compatibility and code clarity.
str vs Text in type hints:
- str is the built-in string type in Python 3.
- Text is imported from the typing module and was introduced for better compatibility between Python 2 and Python 3 during the transition phase.
from typing import Text
def greet(name: Text) -> Text:
return f"Hello, {name}"
Key Differences:
- Text was primarily designed to represent Unicode text in a cross-version compatible way.
- In Python 3, Text is effectively just an alias for str, so there’s no practical difference.
- In Python 2, Text referred to unicode, making it helpful when writing type-annotated code compatible with both versions.
When to use which?
- Use str if you're writing Python 3-only code (which is almost always the case today).
- Use Text only if you’re maintaining code that still targets Python 2 and needs compatibility.
Summary:
- In modern Python (3.5+), using str in type hints is recommended and simpler.
- Text was useful during the Python 2 to 3 migration but is now mostly obsolete.
- Stick with str unless you're dealing with older, multi-version codebases.
So, unless you’re working with legacy Python 2 code, go ahead and use str—it’s clearer and more universally understood in Python 3 projects.