问题描述
typing
模块提供了一个基类通用类型提示:typing.Generic
类.
Generic
的子类接受方括号中的类型参数,例如:
list_of_ints = typing.List[int]str_to_bool_dict = typing.Dict[str, bool]
我的问题是,如何访问这些类型参数?
也就是说,给定 str_to_bool_dict
作为输入,我怎样才能得到 str
和 bool
作为输出?
基本上我正在寻找这样的功能
>>>魔术函数(str_to_bool_dict)(<class 'str'>, <class 'bool'>)Python >= 3.8
从 Python3.8 开始,有 typing.get_args
:
print( get_args( List[int] ) ) # (,)
PEP-560 还提供了 __orig_bases__[n]
,它允许我们使用 n 个泛型基的参数:
from 打字 import TypeVar, Generic, get_argsT = TypeVar(T")类基础(通用[T]):经过派生类( Base[int] ):经过打印(get_args(Derived.__orig_bases__[0]))#(<class 'int'>,)
Python >= 3.6
从 Python 3.6 开始.有一个公共 __args__
和 (__parameters__
) 字段.例如:
print( typing.List[int].__args__ )
这包含泛型参数(即 int
),而 __parameters__
包含泛型本身(即 ~T
).
Python <3.6
一些注意事项
typing
遵循 PEP8.PEP8 和 typing
均由 Guido van Rossum 合着.双前导和尾随下划线定义为:存在于用户控制的命名空间"中的魔法"对象或属性.
dunders 也有内嵌注释;来自打字的官方存储库,我们可以看到:
- "
__args__
是用于下标的所有参数的元组,例如,Dict[T, int].__args__ == (T, int)
".
然而,作者还注意到:
- "打字模块具有临时状态,因此它没有被高标准的向后兼容性所覆盖(尽管我们尽可能地保留它),这对于(尚未记录的)dunder 来说尤其如此
__union_params__
等属性.如果您想在运行时上下文中使用类型,那么您可能对typing_inspect
项目感兴趣(其中的一部分可能会在稍后输入)."
一般来说,无论您使用 typing
做什么,都需要暂时保持最新状态.如果您需要向前兼容的更改,我建议您编写自己的注释类.
The typing
module provides a base class for generic type hints: The typing.Generic
class.
Subclasses of Generic
accept type arguments in square brackets, for example:
list_of_ints = typing.List[int]
str_to_bool_dict = typing.Dict[str, bool]
My question is, how can I access these type arguments?
That is, given str_to_bool_dict
as input, how can I get str
and bool
as output?
Basically I'm looking for a function such that
>>> magic_function(str_to_bool_dict)
(<class 'str'>, <class 'bool'>)
Python >= 3.8
As of Python3.8 there is typing.get_args
:
print( get_args( List[int] ) ) # (<class 'int'>,)
PEP-560 also provides __orig_bases__[n]
, which allows us the arguments of the nth generic base:
from typing import TypeVar, Generic, get_args
T = TypeVar( "T" )
class Base( Generic[T] ):
pass
class Derived( Base[int] ):
pass
print( get_args( Derived.__orig_bases__[0] ) ) # (<class 'int'>,)
Python >= 3.6
As of Python 3.6. there is a public __args__
and (__parameters__
) field.For instance:
print( typing.List[int].__args__ )
This contains the generic parameters (i.e. int
), whilst __parameters__
contains the generic itself (i.e. ~T
).
Python < 3.6
Some considerations
typing
follows PEP8. Both PEP8 and typing
are coauthored by Guido van Rossum. A double leading and trailing underscore is defined in as: ""magic" objects or attributes that live in user-controlled namespaces".
The dunders are also commented in-line; from the official repository for typing wecan see:
- "
__args__
is a tuple of all arguments used in subscripting, e.g.,Dict[T, int].__args__ == (T, int)
".
However, the authors also note:
- "The typing module has provisional status, so it is not covered by the high standards of backward compatibility (although we try to keep it as much as possible), this is especially true for (yet undocumented) dunder attributes like
__union_params__
. If you want to work with typing types in runtime context, then you may be interested in thetyping_inspect
project (part of which may end up in typing later)."
I general, whatever you do with typing
will need to be kept up-to-date for the time being. If you need forward compatible changes, I'd recommend writing your own annotation classes.
这篇关于如何访问typing.Generic 的类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!