Generic functions

Generic type variables can also be used to define generic functions:

  1. from typing import TypeVar, Sequence
  2.  
  3. T = TypeVar('T') # Declare type variable
  4.  
  5. def first(seq: Sequence[T]) -> T: # Generic function
  6. return seq[0]

As with generic classes, the type variable can be replaced with anytype. That means first can be used with any sequence type, and thereturn type is derived from the sequence item type. For example:

  1. # Assume first defined as above.
  2.  
  3. s = first('foo') # s has type str.
  4. n = first([1, 2, 3]) # n has type int.

Note also that a single definition of a type variable (such as Tabove) can be used in multiple generic functions or classes. In thisexample we use the same type variable in two generic functions:

  1. from typing import TypeVar, Sequence
  2.  
  3. T = TypeVar('T') # Declare type variable
  4.  
  5. def first(seq: Sequence[T]) -> T:
  6. return seq[0]
  7.  
  8. def last(seq: Sequence[T]) -> T:
  9. return seq[-1]

A variable cannot have a type variable in its type unless the typevariable is bound in a containing generic class or function.