Generic Type Hints in Python
Level 5365 keystrokes
This creates a generic Stack class using TypeVar. Generics allow type-safe containers that work with any type.
Python code
# Import TypeVar and Generic from typing module# Used for creating generic classes and functions1from typing import TypeVar, Generic2 # T is a type variable representing any type# Acts as placeholder for actual type at usage3T = TypeVar("T")4 # Stack inherits from Generic[T] to be generic# T will be replaced by actual type like int5class Stack(Generic[T]): # __init__ has return type None # Initializes empty stack6 def __init__(self) -> None: # _items is typed as list of T # Stores stack elements7 self._items: list[T] = []8 # push adds item of type T to stack # Returns None9 def push(self, item: T) -> None: # append adds to end of list10 self._items.append(item)11 # pop removes and returns item of type T # Returns the top element12 def pop(self) -> T: # pop removes from end of list13 return self._items.pop()14 # __len__ returns number of items # Called by len() function15 def __len__(self) -> int:16 return len(self._items)17 # Create Stack specifically for integers# Type checker knows stack holds only ints18stack: Stack[int] = Stack()# Push integer 1 onto stack19stack.push(1)# Push integer 2 onto stack20stack.push(2)# Pop returns 2 (last in, first out)21print(stack.pop())Output
2
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.
(× 14)× 14_× 12.× 9:× 8-× 4[× 4]× 4>× 4=× 3