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

MrJ*_*MrJ 3 python type-hinting

考虑以下函数

import typing
def make_list(el : typing.Any):
    return [el, el]
Run Code Online (Sandbox Code Playgroud)

我如何提示它返回

typing.List[type(el)]
Run Code Online (Sandbox Code Playgroud)

dec*_*eze 7

TypeVar就是为了:

from typing import TypeVar, List

T = TypeVar('T')

def make_list(el: T) -> List[T]:
    return [el, el]
Run Code Online (Sandbox Code Playgroud)