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(...)
?
没有评论:
发表评论