Generic Type Variable in Python
Level 5423 keystrokes
This uses TypeVar and Generic to create a type-safe generic class that works with any type while preserving type information.
Python code
# Import typing components for generics1from typing import TypeVar, Generic, List2 # Define type variable for generic type parameter3T = TypeVar("T")4 # Define generic Stack class parameterized by T5class Stack(Generic[T]): # Initialize empty stack6 def __init__(self) -> None: # Internal list (underscore prefix) holding T elements7 self._items: List[T] = []8 # Push item of type T onto stack9 def push(self, item: T) -> None: # Append to internal list10 self._items.append(item)11 # Pop and return top item of type T12 def pop(self) -> T: # Remove and return last item13 return self._items.pop()14 # Check if stack is empty15 def is_empty(self) -> bool: # Return True if no items16 return len(self._items) == 017 # Create Stack specialized for integers18stack: Stack[int] = Stack()# Push first integer19stack.push(1)# Push second integer20stack.push(2)# Pop and print (gets 2: LIFO)21print(f"Popped: {stack.pop()}")# Pop and print (gets 1)22print(f"Popped: {stack.pop()}")Output
Popped: 2 Popped: 1
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 16)× 16:× 10.× 10_× 9"× 6=× 5-× 4[× 4]× 4