Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text vs str, when using python type hints

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()
like image 381
unnobtainium Avatar asked Feb 24 '26 03:02

unnobtainium


1 Answers

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

like image 67
M.X Avatar answered Feb 26 '26 19:02

M.X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!