【发布时间】:2021-01-12 21:02:47
【问题描述】:
今天,我遇到了一个以type 提示的函数类型。
我已经研究了何时应该使用type 或Type 输入提示,但我找不到满意的答案。根据我的研究,两者之间似乎存在一些重叠。
我的问题:
-
type和Type有什么区别? - 什么是显示何时使用
type和Type的示例用例?
研究
查看Type (from typing tag 3.7.4.3)的来源,我可以看到:
# 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 认识到了差异。
【问题讨论】:
标签: python generics type-hinting python-typing