Python Generics: Enhancing Code Reusability and Type Safety

Learn about Python generics and how they enable the creation of functions, classes, and methods that handle multiple types with type safety. Discover how type hints, introduced in Python 3.5, improve code reusability and correctness by specifying expected types for variables, arguments, and return values.



Python - Generics

Generics in Python allow you to define functions, classes, or methods that operate on multiple types while ensuring type safety. This promotes code reusability and type correctness.

Generics are implemented using type hints, introduced in Python 3.5 and later versions. Type hints specify expected types for variables, function arguments, and return values.

Example 1: Generic Function

from typing import List, TypeVar
T = TypeVar('T')

def reverse(items: List[T]) -> List[T]:
    return items[::-1]
Output

# Example usage:
numbers = [1, 2, 3, 4, 5]
reversed_numbers = reverse(numbers)
print(reversed_numbers)  # [5, 4, 3, 2, 1]

fruits = ['apple', 'banana', 'cherry']
reversed_fruits = reverse(fruits)
print(reversed_fruits)  # ['cherry', 'banana', 'apple']
Example 2: Generic Class

from typing import TypeVar, Generic
T = TypeVar('T')

class Box(Generic[T]):
    def __init__(self, item: T):
        self.item = item
    
    def get_item(self) -> T:
        return self.item
Output

# Example usage:
box1 = Box(42)
print(box1.get_item())  # 42

box2 = Box('Hello')
print(box2.get_item())  # Hello