TypeForm[T]: Spelling for regular types (int, str) & special forms (Union[int, str], Literal['foo'], etc) · Issue #9773 · python/mypy (original) (raw)
(An earlier version of this post used TypeAnnotation
rather than TypeForm
as the initially proposed spelling for the concept described here)
Feature
A new special form TypeForm[T]
which is conceptually similar to Type[T]
but is inhabited by not only regular types like int
and str
, but also by anything "typelike" that can be used in the position of a type annotation at runtime, including special forms like Union[int, str]
, Literal['foo']
, List[int]
, MyTypedDict
, etc.
Pitch
Being able to represent something like TypeForm[T]
enables writing type signatures for new kinds of functions that can operate on arbitrary type annotation objects at runtime. For example:
# Returns `value` if it conforms to the specified type annotation using typechecker subtyping rules.
def trycast(typelike: TypeForm[T], value: object) -> Optional[T]: ...
# Returns whether the specified value can be assigned to a variable with the specified type annotation using typechecker subtyping rules.
def isassignable(value: object, typelike: TypeForm[T]) -> bool: ...
Several people have indicated interest in a way to spell this concept:
- @ltworf: Type[T] -> T has a strange behaviour #9003
- @glyph: Type[T] -> T has a strange behaviour #9003 (comment)
- @davidfstr (yours truly): Type[T] -> T has a strange behaviour #9003 (comment)
- @Nico-Kialo: Version 0.780 does not recognize python internal types as typing.Type anymore #8992
- @hmvp: Version 0.780 does not recognize python internal types as typing.Type anymore #8992 (comment)
For a more in-depth motivational example showing how I can use something like TypeForm[T] to greatly simplify parsing JSON objects received by Python web applications, see my recent thread on typing-sig:
If there is interest from the core mypy developers, I'm willing to do the related specification and implementation work in mypy.