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 generics
1from typing import TypeVar, Generic, List
2
# Define type variable for generic type parameter
3T = TypeVar("T")
4
# Define generic Stack class parameterized by T
5class Stack(Generic[T]):
# Initialize empty stack
6 def __init__(self) -> None:
# Internal list (underscore prefix) holding T elements
7 self._items: List[T] = []
8
# Push item of type T onto stack
9 def push(self, item: T) -> None:
# Append to internal list
10 self._items.append(item)
11
# Pop and return top item of type T
12 def pop(self) -> T:
# Remove and return last item
13 return self._items.pop()
14
# Check if stack is empty
15 def is_empty(self) -> bool:
# Return True if no items
16 return len(self._items) == 0
17
# Create Stack specialized for integers
18stack: Stack[int] = Stack()
# Push first integer
19stack.push(1)
# Push second integer
20stack.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

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

More Python examples at level 5

← Python typing practice