Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python Generics Tutorial – Complete Guide with Examples

Python - Generics

When writing Python programs, we often want functions and classes that can work with different data types while still keeping code safe and reusable.

This concept is called Generics.

Generics allow you to write code that works with multiple types (like int, str, list) without rewriting the same logic again and again.

In this tutorial, you will learn what generics are, why they are used, and how to implement them in Python using typing.


What are Generics in Python?

Generics are:

A way to define functions and classes that can work with different data types while maintaining type safety.

Instead of fixing a type, you use a type variable.


Why Use Generics?

Generics help you:

  • Write reusable code
  • Avoid duplication
  • Improve type safety
  • Make code easier to maintain
  • Work with multiple data types

Without Generics (Problem)

If you write separate functions for each type:

def add_int(a: int, b: int) -> int:
    return a + b

def add_str(a: str, b: str) -> str:
    return a + b

This is repetitive and not scalable.


With Generics (Solution)

Python provides generics using the typing module.


Import Required Module

from typing import TypeVar, Generic

What is TypeVar?

TypeVar is used to create a generic type placeholder.

T = TypeVar('T')

Generic Function Example

from typing import TypeVar

T = TypeVar('T')

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

print(get_first_item([1, 2, 3]))
print(get_first_item(["a", "b", "c"]))

How It Works

  • Function works with any type
  • Type is preserved automatically
  • No need to write multiple versions

Generic Class Example

from typing import Generic, TypeVar

T = TypeVar('T')

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

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

int_box = Box[int](10)
str_box = Box[str]("Hello")

print(int_box.get_value())
print(str_box.get_value())

Output

10
Hello

Real Meaning of Generic Class

  • Box[int] → stores integers
  • Box[str] → stores strings
  • Same class, different types

Multiple Type Generics

You can use more than one type variable.

from typing import TypeVar

T = TypeVar('T')
U = TypeVar('U')

def pair(first: T, second: U) -> tuple[T, U]:
    return (first, second)

print(pair(1, "one"))

Output

(1, 'one')

Built-in Generic Types

Python already supports generics in:

  • list[T]
  • dict[K, V]
  • set[T]
  • tuple[T, ...]

Example

def process(data: list[int]) -> list[int]:
    return [x * 2 for x in data]

Generic Constraints (Advanced)

You can restrict types using bounds.

from typing import TypeVar

T = TypeVar('T', int, float)

def add(a: T, b: T) -> T:
    return a + b

Why Constraints are Useful

They ensure:

  • Only valid types are allowed
  • Better safety
  • Fewer runtime errors

Generics vs Normal Functions

FeatureNormal FunctionGeneric Function
ReusabilityLowHigh
Type SafetyMediumHigh
FlexibilityLowHigh

Real-World Example

Generic Data Storage System

from typing import Generic, TypeVar

T = TypeVar('T')

class Storage(Generic[T]):
    def __init__(self):
        self.data: list[T] = []

    def add(self, item: T):
        self.data.append(item)

    def get_all(self) -> list[T]:
        return self.data

int_store = Storage[int]()
int_store.add(10)
int_store.add(20)

print(int_store.get_all())

Where Generics Are Used

Generics are widely used in:

  • APIs
  • Data structures
  • Frameworks
  • Libraries (like FastAPI, Pydantic)
  • Type-safe applications

Advantages of Generics

  • Code reuse
  • Cleaner architecture
  • Strong type checking
  • Better IDE support
  • Reduced duplication

Limitations

  • Slightly more complex for beginners
  • Mainly useful for large projects
  • No runtime enforcement (only type hints)

Common Mistakes

1. Using Generics without typing module


2. Overusing TypeVar unnecessarily


3. Ignoring type hints


Best Practices

1. Use generics for reusable structures


2. Keep type variables simple


3. Use meaningful TypeVar names

T = TypeVar('T')
K = TypeVar('K')
V = TypeVar('V')

Summary

Generics in Python allow you to write flexible and reusable code that works with multiple data types while maintaining type safety. They are essential for modern Python development, especially in large-scale applications.

Key Takeaways

  • Generics allow reusable type-safe code
  • Use TypeVar to define generic types
  • Generic[T] is used for classes
  • Built-in support exists in list, dict, tuple
  • Widely used in modern frameworks
  • Improves maintainability and scalability

Mastering generics will help you write cleaner, more professional Python code for real-world applications.




Post a Comment

0 Comments