Issue
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.)
Solution
Answer for Python 3.10:
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 | float
(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._BaseGenericAlias
that first appeared in their inheritance chain. (In fact, not only these, but almost all subscriptible annotation classes intyping
inherit 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.
Python 3.11 update:
I noticed that typing.Any
has changed from typing._SpecialForm
to typing._AnyMeta
(to allow inheritance of it), but it is now a type
(which we have already included) and we don't need to add anything new to it.
typing.Self
and typing.LiteralString
have been added in 3.11, but they are both typing._SpecialForm
, so there is also no need for anything new.
Python 3.12 update:
We now have a type
statement, which allows us to create typing.TypeAliasType
object, this seems to be the only new content.
Answered By - Mechanic Pig
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.