I have a use case for accepting type hints as arguments to a function. But what is the right type hint to to accept a type hint?
T = TypeVar('T', bound='TypeHintType')
def register_handler(type_hint: T, handler: Handler[T]) -> None:
...
Is there a "TypeHintType" that I can use to annotate that a type hint is expected as an argument?
Currently there is no such thing yet. But, there is one in the making in PEP 747 - Annotating Type Forms by some prominent figures in Python's typing ecosystem.
An argument that should be a type-hint itself will be called a TypeForm
.
Or, more concrete
A [TypeForm is a] special form representing the value of a type expression.
TypeForm
might come with Python 3.14.
Nevertheless, TypeForm
is already supported by pyright
with experimental features enabled(*). And a backport is provided by typing_extensions
, however, it is not released yet and will come in typing_extensions 4.13 that should arrive soon.
It can then, for example be used like this:
from typing_extensions import TypeForm
def register_handler[T](type_hint: TypeForm[T], handler: Handler[T]) -> None:
...
register_handler(int | float, yourobject)
Some nice use cases are (taken from the PEP):
def is_assignable[T](value: object, typx: TypeForm[T]) -> TypeIs[T]
def is_match[T](value: object, typx: TypeForm[T]) -> TypeGuard[T]
def convert[T](value: object, typx: TypeForm[T]) -> T
(*) To enable experimental features in pyright use you need the following line in your pyproject.toml file.
[tool.pyright]
enableExperimentalFeatures = true
Note: As PEP 747 is still in its draft phase, there might be changes.
Some discussions about PEP 747: