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 functions
1from typing import TypeVar, Generic
2
# T is a type variable representing any type
# Acts as placeholder for actual type at usage
3T = TypeVar("T")
4
# Stack inherits from Generic[T] to be generic
# T will be replaced by actual type like int
5class Stack(Generic[T]):
# __init__ has return type None
# Initializes empty stack
6 def __init__(self) -> None:
# _items is typed as list of T
# Stores stack elements
7 self._items: list[T] = []
8
# push adds item of type T to stack
# Returns None
9 def push(self, item: T) -> None:
# append adds to end of list
10 self._items.append(item)
11
# pop removes and returns item of type T
# Returns the top element
12 def pop(self) -> T:
# pop removes from end of list
13 return self._items.pop()
14
# __len__ returns number of items
# Called by len() function
15 def __len__(self) -> int:
16 return len(self._items)
17
# Create Stack specifically for integers
# Type checker knows stack holds only ints
18stack: Stack[int] = Stack()
# Push integer 1 onto stack
19stack.push(1)
# Push integer 2 onto stack
20stack.push(2)
# Pop returns 2 (last in, first out)
21print(stack.pop())

Output

2
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.

  • (× 14
  • )× 14
  • _× 12
  • .× 9
  • :× 8
  • -× 4
  • [× 4
  • ]× 4
  • >× 4
  • =× 3

More Python examples at level 5

← Python typing practice