Course contentsShow
← Python
Lesson 561 of 1,0609. Type Safety and Code QualityFree lesson

Defining Generic Functions with TypeVar

You will learn to create functions that operate on multiple types while maintaining type consistency between input arguments and return values.

In this lesson, you will learn how to create flexible, reusable functions that handle multiple data types while ensuring the return value remains consistent with the input type.

The Problem with Fixed Types

When you annotate a function, you usually specify exact types, like int or str. But what if you have a function that simply returns the first element of a list? If you annotate it to accept only list[int], it won't work for list[str]. If you use list[Any], you lose all the helpful information about what kind of data is coming back.

Enter TypeVar

TypeVar allows you to define a "placeholder" for a type that is determined only when the function is actually called. Think of it as a variable for types. By importing TypeVar from the typing module, you can tell your static type checker (like mypy) that the input and output are linked, even if the specific type is unknown at the time you write the code.

Here is how you define it:

from typing import TypeVar, List

# Define a TypeVar placeholder named 'T'
T = TypeVar('T')

def get_first(items: List[T]) -> T:
    return items[0]

# Now, static checkers know that if you pass a list of strings,
# you get a string back.
reveal_type(get_first(["apple", "banana"]))  # Output: str
reveal_type(get_first([1, 2, 3]))            # Output: int

Why This Matters

In the example above, T acts as a generic constraint. When you pass a List[str], the type checker internally treats T as str for that specific call. This keeps your code flexible—you don't need to write separate functions for integers, strings, or custom objects—but strict enough that you won't accidentally treat the output of get_first([1, 2]) as a string.

Generic functions prevent "type dilution" (where you lose track of what your data is) while keeping your codebase DRY (Don't Repeat Yourself). It is the bridge between writing overly specific code and writing code that is too loosely typed to be safe.

Key Takeaway: Use TypeVar to create generic functions that maintain strict type relationships between inputs and outputs, allowing one function to safely handle multiple types.