All categories
    PythonAdvanced

    Type Hints

    Python type hints with runnable examples: parameters, return types, variables, Optional, multiple return values, *args and **kwargs, and generators.

    On this page

    01Annotate a function

    main.py
    def greet(name: str) -> str:
        return "Hello, " + name
    
    print(greet("World"))
    Output
    Hello, World

    02Variable annotations

    main.py
    age: int = 25
    height: float = 1.75
    name: str = "Ada"
    print(age, height, name)
    Output
    25 1.75 Ada

    03Typed list parameter

    main.py
    from typing import List
    def total(nums: List[int]) -> int:
        return sum(nums)
    
    print(total([1, 2, 3, 4]))
    Output
    10

    04Optional return value

    main.py
    from typing import Optional
    def find(x: int) -> Optional[str]:
        if x > 0:
            return "positive"
        return None
    
    print(find(5))
    print(find(-1))
    Output
    positive
    None

    05Return multiple values

    main.py
    def min_max(numbers: list[int]) -> tuple[int, int]:
        return min(numbers), max(numbers)
    
    low, high = min_max([4, 9, 1, 7])
    print(low, high)
    Output
    1 9

    06Type hints for *args and **kwargs

    main.py
    # *tags: str means every extra positional argument is a str.
    # **scores: int means every keyword argument's value is an int.
    def describe(*tags: str, **scores: int) -> str:
        total = sum(scores.values())
        return f"{', '.join(tags)}: {total} points"
    
    print(describe("math", "quiz", alice=8, bob=7))
    Output
    math, quiz: 15 points

    07Type hint for a generator

    main.py
    from collections.abc import Iterator
    
    def countdown(n: int) -> Iterator[int]:
        while n > 0:
            yield n
            n -= 1
    
    print(list(countdown(3)))
    Output
    [3, 2, 1]