Skip to content

Type annotations and union types [ref]

Problem

  • Annotate a sum function accepting list[int] and returning int.
  • Annotate a variable that can contain a Node or None.
  • Annotate a function returning a pair of an optional Node and a Node.
  • Quote a self-referential constructor annotation so it can be evaluated when the class is defined.

Python solution

def total(nums: list[int]) -> int:
    return sum(nums)

total([1, 2, 3])  # 6

class Node:
    def __init__(self, val: int, next: "Node | None" = None):
        self.val = val
        self.next = next

head: Node | None = Node(1)
head.val  # 1

def ends(node: Node) -> tuple[Node | None, Node]:
    return node.next, node

ends(head)[1].val  # 1