Generic Typing in Python
Generic typing in Python allows developers to create more flexible and reusable code by defining types that work with multiple data types. This is especially useful for functions and classes that need to handle a variety of types but still enforce type safety. Here are the main elements of generic typing:
Type Variables (TypeVar):
A TypeVar allows you to define a generic type variable that can be used to create functions or classes that work with multiple types. For example:
from typing import TypeVar, List
T = TypeVar('T') # Generic type variable
def get_first_element(lst: List[T]) -> T:
return lst[0]
Here, T can be any type, and get_first_element can be used with lists of any type.
Generic Classes:
You can create classes that operate on multiple types by using TypeVar within the class definition. For example:
from typing import Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self):
self.items: List[T] = []
def push(self, item: T):
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
This Stack class can hold elements of any type, and the type is enforced by TypeVar.
Union and Optional:
When a function can accept more than one type, Union can be used to specify multiple allowed types, while Optional is shorthand for Union[type, None]. For example:
from typing import Union, Optional
def display(value: Union[int, str]):
print(value)
def get_username(user_id: int) -> Optional[str]:
# returns a string or None
return None # or some string based on logic
Parameterized Collections:
Generic types can also be used with built-in collections like List, Dict, and Tuple. For example:
from typing import List, Dict
def process_items(items: List[str]):
# List containing only strings
for item in items:
print(item.upper())
Using generics improves code readability and reliability by ensuring types are consistent and well-defined. This is particularly valuable in large codebases and projects where type safety helps avoid errors freddys-menu.com