获取列表类型的元素类型 [英] Get element type of list type

查看:43
本文介绍了获取列表类型的元素类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些列表类型(来自 inspect.signature -> inspect.Parameter),我想了解它们的元素类型.我当前的解决方案有效但非常丑陋,请参阅下面的最小示例:

from 打字 import List, Type, TypeVarTypeT = TypeVar('TypeT')IntList = List[int]StrList = 列表[str]# todo: 不用字符串表示和 eval 求解def list_elem_type(list_type: Type[TypeT]) ->类型[TypeT]:断言 str(list_type)[:11] == 'typing.List'return eval(str(list_type)[12:-1]) # 类型:忽略断言 list_elem_type(IntList) 是 int断言 list_elem_type(StrList) 是 str

获取List元素类型的正确方法是什么?

(我使用的是 Python 3.6,代码应该可以通过 mypy --strict 进行检查.)

解决方案

相信您应该能够检查 __args__ 参数:

<预><代码>>>>从输入导入字典、列表、类型、TypeVar>>>列表[字典].__args__(打字.字典,)>>>列表[int].__args__(<class 'int'>,)

但请注意 docs:

<块引用>

注意 打字模块已临时包含在标准库中.可能会添加新功能,API 可能会更改如果核心认为有必要,即使在次要版本之间开发人员.

所以这可能不是未来的证明.

I have some list types (coming from inspect.signature -> inspect.Parameter) and I'd like to get to know the type of their elements. My current solution works but is extremely ugly, see minimal example below:

from typing import List, Type, TypeVar

TypeT = TypeVar('TypeT')

IntList = List[int]
StrList = List[str]

# todo: Solve without string representation and eval
def list_elem_type(list_type: Type[TypeT]) -> Type[TypeT]:
    assert str(list_type)[:11] == 'typing.List'
    return eval(str(list_type)[12:-1]) # type: ignore

assert list_elem_type(IntList) is int
assert list_elem_type(StrList) is str

What would be the correct way to get the type of a List's elements?

(I'm using Python 3.6 and the code should survive a check with mypy --strict.)

解决方案

I believe that you should be able to check the __args__ parameter:

>>> from typing import Dict, List, Type, TypeVar
>>> List[Dict].__args__
(typing.Dict,)
>>> List[int].__args__
(<class 'int'>,)

But note from the docs:

Note The typing module has been included in the standard library on a provisional basis. New features might be added and API may change even between minor releases if deemed necessary by the core developers.

So this probably isn't future proof.

这篇关于获取列表类型的元素类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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