I have a function one of whose arguments is expected to be a type hint: something like typing.List, or typing.List[int], or even just int. Anything you would reasonably expect to see as a type annotation to an ordinary field.
What's the correct type hint to put on this argument?
(The context for this is that I'm writing a utility that works on classes that define fields using type annotations, a bit like the dataclass decorator.)
CodePudding user response:
Almost complete but less readable answer:
type | types.GenericAlias | types.UnionType | typing._BaseGenericAlias | typing._SpecialForm
Here are the possibilities of all types of annotations I can think of:
- Type object itself, such as
int,list, etc. Corresponds totype. - Type hinting generics in standard collections, such as
list[int]. Corresponds totypes.GenericAlias. - Types union, such as
int | floas(buttyping.Union[int, float]is not, it corresponds to the next item). Corresponds totypes.UnionType. - Generic concrete collections in
typing, such astyping.List,typing.List[int], etc. Here I choose the common base classtyping._BaseGenericAliasthat first appeared in their inheritance chain. (In fact, not only these, but almost all subscriptible annotation classes intypinginherit from this class, includingtyping.Literal[True],typing.Union[int, float], etc.) - Special typing primitives in typing, such as
typing.Any,typing.NoReturn, etc. Corresponds totyping._SpecialForm.
It should be noted that the last two types begin with a single underline, indicating that they are internal types, and should not be imported and used from typing. However, they should be indispensable if you insist on completely covering all type annotations.
