Python 打字中的 Literal 和 Union 有什么区别?

What's the difference between Literal and Union in Python typing?

在 Python 打字中 LiteralUnion 有什么区别?

我看不出它们有什么区别。 谁能解释一下?

当我使用 Union[2,3] 时,我的 IDE 没有回应我。

Union[x, y] 表示 "either x or y". Literal[5, 6] means "literally 5 or literally 6"(不是等于其中任何一个的变量,而是 字面意思 56 ).

区别在于Union的参数必须是类型Literal 的参数是 文字 。类型名称(如 intfloatMyClass)不是文字(但它们确实表示类型),因此不能在 Literal 中使用。文字(如 5'Hello!'[1,2,3])不是类型,因此不能在 Union.

中使用

例如,这些类型不正确:

Literal[str, float]  # none of the arguments are literals
Union[5, 6] # none of the arguments are types

针对您的评论,None 文字和类型。

None 被定义为 Python's grammar 中的文字:

atom: ('(' [yield_expr|testlist_comp] ')' |
       '[' [testlist_comp] ']' | # maybe list literal
       '{' [dictorsetmaker] '}' | # maybe dict/set literal
       NAME |  # NOT a literal
       NUMBER | # int/float literal
       STRING+ | # string literal
       '...' | # Ellipsis literal
       'None' | # None literal!
       'True' | 'False')

这里的None是一个字面量,所以可以用在Literal中。但是,不是而是class:

>>> import inspect
>>> inspect.isclass(None)
False
>>> inspect.isclass(5)
False
>>> inspect.isclass(str)
True

所以,它不能在Union中使用。 但是它实际上用于UnionUnion[str, None]表示"type str or nothing"。来自 Union 上的文档:

You can use Optional[X] as a shorthand for Union[X, <b>None</b>]