Today, I came across a function type hinted with type
.
I have done some research as to when one should type hint with type
or Type
, and I can't find a satisfactory answer. From my research it seems there's some overlap between the two.
My question:
- What is the difference between
type
andType
? - What is an example use case that shows when to use
type
vsType
?
Research
Looking at the source for Type
(from typing
tag 3.7.4.3
), I can see this:
# 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. ```
It looks like Type
may just be an alias for type
, except it supports Generic
parameterization. Is this correct?
Example
Here is some sample code made using Python==3.8.5
and 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]"
Clearly mypy
recognizes a difference.