在您的构造上使用.__args__。所以你需要的神奇功能是--
get_type_args = lambda genrc_type: getattr(genrc_type, '__args__')
我的问题是,如何访问这些类型参数?
在这种情况下——我该如何访问...
使用 Python 强大的自省功能。
即使作为非专业程序员,我也知道我正在尝试检查东西,dir 是一个类似于终端中的 IDE 的函数。所以之后
>>> import typing
>>> str_to_bool_dict = typing.Dict[str, bool]
我想看看有没有什么东西可以做你想要的魔法
>>> methods = dir(str_to_bool_dict)
>>> methods
['__abstractmethods__', '__args__', .....]
我看到的信息太多,为了看看我是否正确,我验证了
>>> len(methods)
53
>>> len(dir(dict))
39
现在让我们找到专门为泛型类型设计的方法
>>> set(methods).difference(set(dir(dict)))
{'__slots__', '__parameters__', '_abc_negative_cache_version', '__extra__',
'_abc_cache', '__args__', '_abc_negative_cache', '__origin__',
'__abstractmethods__', '__module__', '__next_in_mro__', '_abc_registry',
'__dict__', '__weakref__'}
其中,__parameters__、__extra__、__args__ 和 __origin__ 听起来很有帮助。 __extra__ 和 __origin__ 没有 self 将无法工作,所以我们只剩下 __parameters__ 和 __args__。
>>> str_to_bool_dict.__args__
(<class 'str'>, <class 'bool'>)
这就是答案。
Introspection 允许 py.test 的 assert 语句使 JUnit 派生的测试框架看起来过时了。甚至像 JavaScript / Elm / Clojure 这样的语言也没有像 Python 的 dir 这样的直截了当的东西。 Python 的命名约定允许您在不实际阅读(在某些情况下例如摸索)文档的情况下发现该语言。
因此,请使用自省并阅读文档/邮件列表来确认您的发现。
附:致 OP——如果你不能提交邮件列表或者是一个忙碌的开发人员,这个方法还可以回答你的问题What's the correct way to check if an object is a typing.Generic? 使用发现——这就是在 python 中实现它的方法。