Python Mastery – From Basics to Brilliance / Type Hints and Code Quality

Generics - Basic Introduction

🧬 Generics

Generics allow you to write reusable code that can work with different data types while still keeping type hints.

Instead of writing separate functions for int, str, etc., we can write one generic function.


🔹 Basic Example

from typing import TypeVar

T = TypeVar("T")

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

🔹 Generic Classes

Generics can also be used with classes:

from typing import Generic, TypeVar

T = TypeVar("T")

class Box(Generic[T]):
    def __init__(self, value: T):
        self.value = value

    def get(self) -> T:
        return self.value

Now:

number_box = Box[int](100)
name_box = Box[str]("Tisha")

Generic = Write once, use with multiple types.