如何访问type.generic的类型参数? [英] How to access the type arguments of typing.Generic?

查看:109
本文介绍了如何访问type.generic的类型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typing 模块为通用类型提示提供了一个基类: typing.Generic 类.

Generic的子类接受方括号中的类型参数,例如:

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?

也就是说,给定str_to_bool_dict作为输入,如何获得strbool作为输出?

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更新

从Python3.8开始,有typing.get_args:

print( get_args( List[int] ) ) # (<class 'int'>,)

PEP-560 还提供了__orig_bases__[n],它使我们能够第 n 个通用基的参数:

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'>,)

旧答案

可能性1

自Python 3.6起.有一个公共的__args__和(__parameters__)字段. 例如:

As of Python 3.6. there is a public __args__ and (__parameters__) field. For instance:

print( typing.List[int].__args__ )

这包含通用参数(即int),而__parameters__包含通用本身(即~T).

This contains the generic parameters (i.e. int), whilst __parameters__ contains the generic itself (i.e. ~T).

可能性2

使用 typing_inspect.getargs

使用哪个

typing遵循 PEP8 . PEP8和typing均由Guido van Rossum合着.开头和结尾的双下划线定义为:"生活在用户控制的命名空间"中的魔术"对象或属性.

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".

雷声也被在线注释;从输入的官方存储库中 可以看到: * "__args__是用于下标的所有参数的元组,例如Dict[T, int].__args__ == (T, int)".

The dunders are also commented in-line; from the official repository for typing we can see: * "__args__ is a tuple of all arguments used in subscripting, e.g., Dict[T, int].__args__ == (T, int)".

但是,作者还指出了: * 类型模块具有临时状态,因此它没有被高标准的向后兼容性所覆盖(尽管我们尝试尽可能地保持它),这对于(但未记录)dunder属性(例如__union_params__.如果您想在运行时上下文中使用键入类型,那么您可能会对typing_inspect项目感兴趣(其中一部分可能会在以后键入)."

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 the typing_inspect project (part of which may end up in typing later)."

一般来说,无论您对typing所做的任何操作,都需要暂时保持最新.如果您需要向前兼容的更改,建议您编写自己的注释类.

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.

这篇关于如何访问type.generic的类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆