【问题标题】:How to check TypeVar's Type at runtime如何在运行时检查 TypeVar 的类型
【发布时间】:2020-06-20 09:19:47
【问题描述】:

我有一个通用类Graph[Generic[T], object]
我的问题,是否有任何函数返回作为泛型传递给类Graph

>>> g = Graph[int]()
>>> magic_func(g)
<class 'int'>

【问题讨论】:

标签: python generics static-typing


【解决方案1】:

这是一种在 Python 3.6+ 上工作的方法(在 3.6、3.7 和 3.8 中测试过):

from typing import TypeVar, Generic

T = TypeVar('T')

class Graph(Generic[T], object):
    def get_generic_type(self):
        print(self.__orig_class__.__args__[0])


if __name__=='__main__':
    g_int = Graph[int]()
    g_str = Graph[str]()

    g_int.get_generic_type()
    g_str.get_generic_type()

输出:

<class 'int'>
<class 'str'>

如果您想在 __new____init__ 中获取类型,事情会有些棘手,请参阅以下帖子了解更多信息:Generic[T] base class - how to get type of T from within instance?

编辑

pytypes 库似乎提供了一种允许从 init 获取 orig_class 的方法,请在此处查看方法 get_orig_classhttps://github.com/Stewori/pytypes/blob/master/pytypes/type_util.py

【讨论】:

    猜你喜欢
    • 2013-11-02
    • 2014-06-02
    • 2011-12-04
    • 2014-09-13
    • 1970-01-01
    • 2012-01-27
    • 2016-09-09
    • 1970-01-01
    • 2016-07-15
    相关资源
    最近更新 更多