类型注释:输入和输出类型之间的依赖关系

Type annotation: dependencies between input and output types

现在我有一个功能:

def foo(a: List) -> Any:
    return a[1]

我需要避免 Any 并且有类似的东西:

def foo(a: List[T]) -> T:
    return a[1]

可能吗?

是的,它叫做 typing.TypeVar:

import typing

T = typing.TypeVar("T")

def foo(a: typing.Sequence[T]) -> T:
    return a[1]

x = "a"
x = foo([1])
# error: Incompatible types in assignment (expression has type "int", variable has type "str")