2021年4月1日星期四

Understanding usage of TypeVar

When speaking about Generics, python gives the following example:

from collections.abc import Sequence  from typing import TypeVar    T = TypeVar('T')      # Declare type variable    def first(l: Sequence[T]) -> T:   # Generic function      return l[0]  

Could someone please explain what TypeVar does in this case? For example, if it can be anything why not just give it the value Any? And if it's constrained, why not give it a Union value? In other words, what is the usefulness of using TypeVar(...)?

https://stackoverflow.com/questions/66913950/understanding-usage-of-typevar April 02, 2021 at 11:06AM

没有评论:

发表评论