typy

beta

Functions

Typing functions looks like this:

def occupancy(channel: str, count: int = 0) -> str:
    return f"There are {count} people in #{channel}"

Typing the parameters is just like typing variables. The type of the return value is indicated by -> str.

The type checker should prevent us from calling this function with incorrect arguments:

occupancy("pets")
occupancy("pets", 42)
occupancy("pets", "a lot of")
#> Argument of type "str" cannot be assigned to parameter "count" of type "int" in function "occupancy"

It should also prevent us from accidentally changing the return value of the function to something incompatible:

def occupancy(channel: str, count: int = 0) -> str:
    if not count:
        return None
        #> Expression of type "None" cannot be assigned to return type "str"
    return f"There are {count} people in #{channel}"

Callable

Sometimes we need to type a value which is itself a function. This can be done with the Callable type:

Callable[[Arg1, Arg2, ...], ReturnType]

We could type our above function like so:

from typing import Callable

def occupancy(channel: str, count: int):
    return f"There are {count} people in #{channel}"

fn: Callable[[str, int], str] = occupancy