使用 python 类型提示时,Text 与 str

unn*_*ium 12 python string annotations python-3.x python-typing

在键入注释字符串、文本或 str 时应该使用什么?使用时有什么区别?

例如:

from typing import Text
def spring(a: Text) -> Text:
    return a.upper()
Run Code Online (Sandbox Code Playgroud)

或者

def spring(a: str) -> str:
    return a.upper()
Run Code Online (Sandbox Code Playgroud)

Zci*_*rus 14

来自文档(正如 Ians 评论中提到的):

Text是 的别名str。提供它是为了为 Python 2 代码提供向前兼容的路径:在 Python 2 中,Textunicode.

使用 Text 指示值必须以与 Python 2 和 Python 3 兼容的方式包含 unicode 字符串:

def add_unicode_checkmark(text: Text) -> Text:
   return text + u' \u2713' 
Run Code Online (Sandbox Code Playgroud)

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

  • 我觉得这个答案也应该说:“但是对于仅 Python3 的代码,只需使用 `str`。” (13认同)