Python 打字中的 Literal 和 Union 有什么区别?
What's the difference between Literal and Union in Python typing?
在 Python 打字中 Literal
和 Union
有什么区别?
我看不出它们有什么区别。
谁能解释一下?
当我使用 Union[2,3]
时,我的 IDE 没有回应我。
Union[x, y]
表示 "either x
or y
". Literal[5, 6]
means "literally 5
or literally 6
"(不是等于其中任何一个的变量,而是 字面意思 5
或 6
).
区别在于Union
的参数必须是类型。 Literal
的参数是 文字 。类型名称(如 int
、float
、MyClass
)不是文字(但它们确实表示类型),因此不能在 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
中使用。 但是它实际上是用于Union
:Union[str, None]
表示"type str
or nothing"。来自 Union
上的文档:
You can use Optional[X]
as a shorthand for Union[X, <b>None</b>]
在 Python 打字中 Literal
和 Union
有什么区别?
我看不出它们有什么区别。 谁能解释一下?
当我使用 Union[2,3]
时,我的 IDE 没有回应我。
Union[x, y]
表示 "either x
or y
". Literal[5, 6]
means "literally 5
or literally 6
"(不是等于其中任何一个的变量,而是 字面意思 5
或 6
).
区别在于Union
的参数必须是类型。 Literal
的参数是 文字 。类型名称(如 int
、float
、MyClass
)不是文字(但它们确实表示类型),因此不能在 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
中使用。 但是它实际上是用于Union
:Union[str, None]
表示"type str
or nothing"。来自 Union
上的文档:
You can use
Optional[X]
as a shorthand forUnion[X, <b>None</b>]