Generic Type (TypeVar)

say it: “TYP VAR” /taɪp vɑːr/ or “juh-NAIR-ik TYP” /dʒəˈnɛrɪk taɪp/

Lets code work with any type while keeping in and out types linked.

What is a generic type?

A generic type lets a function or class work with any type while keeping the types linked: whatever type goes in is the type that comes out.

from typing import TypeVar

T = TypeVar("T")

def first_in_line(queue: list[T]) -> T:
    return queue[0]

name = first_in_line(["Ana", "Ben"])   # tools know this is a str

Level: Freelancer · More Python terms at this level

Updated