问题
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
.)
回答1:
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.
来源:https://stackoverflow.com/questions/51578145/get-element-type-of-list-type