今天,我遇到了一个用
我已经做了一些研究,想知道何时应该使用
我的问题是:
type
进行类型提示的函数。我已经做了一些研究,想知道何时应该使用
type
或Type
进行类型提示,但我找不到令人满意的答案。从我的研究中,似乎这两者之间存在一些重叠。我的问题是:
type
和Type
之间有什么区别?- 什么是示例用例,展示了何时使用
type
和Type
?
研究
查看typing
标记3.7.4.3
的源代码Type
(来自typing
),我可以看到这个:
# Internal type variable used for Type[].
CT_co = TypeVar('CT_co', covariant=True, bound=type)
# This is not a real generic class. Don't use outside annotations.
class Type(Generic[CT_co], extra=type):
"""A special construct usable to annotate class objects. ```
看起来Type
可能只是type
的别名,但它支持Generic
参数化。这个理解正确吗?
示例
这是使用Python==3.8.5
和mypy==0.782
编写的一些示例代码:
from typing import Type
def foo(val: type) -> None:
reveal_type(val) # mypy output: Revealed type is 'builtins.type'
def bar(val: Type) -> None:
reveal_type(val) # mypy output: Revealed type is 'Type[Any]'
class Baz:
pass
foo(type(bool))
foo(Baz)
foo(Baz()) # error: Argument 1 to "foo" has incompatible type "Baz"; expected "type"
bar(type(bool))
bar(Baz)
bar(Baz()) # error: Argument 1 to "bar" has incompatible type "Baz"; expected "Type[Any]"
显然,mypy
识别出了一个差异。