Skip to content
BetaDE
Lesson 33 of 35Python

Python · Lesson 33 · 20 minutes

Type hints

What you'll learn

  • Label parameters and return values with types
  • Read list[int], dict[str, int] and optional values
  • Use dataclasses for simple data objects

What’s in the variable?

Python doesn’t care which type a variable has. But for people (and editors) it’s very helpful to know what a function expects. Type hints write that right next to it:

def introduce(name: str, age: int) -> str:
    return f"{name} is {age} years old."

print(introduce("Mia", 12))
print(introduce.__annotations__)

After the colon comes the type of a parameter, after -> the type of the return value.

Important: Python does not check the types when running. Hints are labels – but tools like mypy or your editor use them to warn you about mistakes before the program runs.

Types for lists and dictionaries

def best_team(points: dict[str, int]) -> str:
    return max(points, key=points.get)

def only_even(numbers: list[int]) -> list[int]:
    return [n for n in numbers if n % 2 == 0]

def find(names: list[str], wanted: str) -> int | None:
    if wanted in names:
        return names.index(wanted)
    return None

print(best_team({"Red": 3, "Blue": 7}))
print(only_even([1, 2, 3, 4]))
print(find(["Mia", "Ben"], "Tom"))

int | None means: “a number – or nothing at all”.

Dataclasses

For classes that mainly store data there’s a shortcut. @dataclass writes __init__ and a nice display for you – from the type hints:

from dataclasses import dataclass

@dataclass
class Robot:
    name: str
    battery: int = 100

r = Robot("Robo")
print(r)
r.battery -= 15
print(r.battery)

Quick check

Before you start the task: what does this program print? Type your guess – then Python works it out.

def area(width: int, height: int) -> int:
    return width * height


print(area(3, 4), area("ab", 2))

Your task

Your turn

Add type hints to the function average: it gets a list of decimals (list[float]) and returns a decimal (float). For an empty list it should return 0.0. Also create a dataclass Player with name: str and points: int.

from dataclasses import dataclass


def average(values):
    return sum(values) / len(values)


# Dataclass Player


print(average([2.0, 3.0, 4.0]))
print(average([]))

Solve it without hints to earn a ⭐ on your progress page.

Show solution

Try it yourself first – mistakes teach you the most. Here is one possible solution:

from dataclasses import dataclass


def average(values: list[float]) -> float:
    if not values:
        return 0.0
    return sum(values) / len(values)


@dataclass
class Player:
    name: str
    points: int


print(average([2.0, 3.0, 4.0]))
print(average([]))