简体   繁体   English

如何键入提示其值本身就是类型提示的变量?

[英]How do I type hint a variable whose value is itself a type hint?

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 .我有一个 function ,其中一个 arguments 应该是一个类型提示:类似于typing.Listtyping.List[int] ,甚至只是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.) (上下文是我正在编写一个实用程序,该实用程序适用于使用类型注释定义字段的类,有点像 dataclass 装饰器。)

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 to type .类型 object 本身,如intlist等,对应type
  • Type hinting generics in standard collections , such as list[int] .在标准 collections 中键入提示 generics ,例如list[int] Corresponds to types.GenericAlias .对应于types.GenericAlias
  • Types union , such as int | floas 类型 union ,例如int | floas int | floas (but typing.Union[int, float] is not, it corresponds to the next item). int | floas (但typing.Union[int, float]不是,它对应于下一项)。 Corresponds to types.UnionType .对应于types.UnionType
  • Generic concrete collections in typing , such as typing.List , typing.List[int] , etc. Here I choose the common base class typing._BaseGenericAlias that first appeared in their inheritance chain. 泛型具体 collectionstyping中,如typing.Listtyping.List[int]等。这里我选择公共基础 class typing._BaseGenericAlias ,第一次出现在他们的 Z5FED3411FAF832174EF1F04002 链中。 (In fact, not only these, but almost all subscriptible annotation classes in typing inherit from this class, including typing.Literal[True] , typing.Union[int, float] , etc.) (其实不只是这些, typing中几乎所有的下标注解类都继承自这个class,包括typing.Literal[True]typing.Union[int, float]等)
  • Special typing primitives in typing, such as typing.Any , typing.NoReturn , etc. Corresponds to typing._SpecialForm .打字中的特殊打字原语,例如打字typing.Any ,打字typing.NoReturn等。对应于typing._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 .需要注意的是,后两种类型以单下划线开头,表示它们是内部类型,不应从typing中导入和使用。 However, they should be indispensable if you insist on completely covering all type annotations.但是,如果您坚持完全覆盖所有类型注释,它们应该是必不可少的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM