Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork3k
Description
(An earlier version of this post usedTypeAnnotation
rather thanTypeForm
as the initially proposed spelling for the concept described here)
Feature
A new special formTypeForm[T]
which is conceptually similar toType[T]
but is inhabited by not only regular types likeint
andstr
, but also by anything "typelike" that can be used in the position of a type annotation at runtime, including special forms likeUnion[int, str]
,Literal['foo']
,List[int]
,MyTypedDict
, etc.
Pitch
Being able to represent something likeTypeForm[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.