12

What should I use when type annotating a string, Text, or str. What is the difference when using either?

for ex:

from typing import Text
def spring(a: Text) -> Text:
    return a.upper()

or

def spring(a: str) -> str:
    return a.upper()
4

1 Answer 1

15

From the docs (As mentioned in Ians comment):

Text is an alias for str. It is provided to supply a forward compatible path for Python 2 code: in Python 2, Text is an alias for unicode.

Use Text to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:

def add_unicode_checkmark(text: Text) -> Text:
   return text + u' \u2713' 

https://docs.python.org/3/library/typing.html#typing.Text

1
  • 14
    I feel like this answer should also say: "but for Python3-only code, just use str."
    – Carl G
    Commented Sep 9, 2021 at 17:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.