Python 类型提示,输出类型取决于输入类型

Python type hinting, output type depends on input type

考虑以下函数

import typing
def make_list(el : typing.Any):
    return [el, el]

我如何暗示它 returns

typing.List[type(el)]

这就是 TypeVar 的用途:

from typing import TypeVar, List

T = TypeVar('T')

def make_list(el: T) -> List[T]:
    return [el, el]