hayaliv

hayaliv / Hi! Python / Level 2

Type hints

Type hints label what a variable or function expects. Python does not enforce them, but tools such as type checkers can read them.

Hi! Python · Level 2: Level 2: Writing reliable code · Checked against the Python 3.12 documentation · Updated 2026-10-17

Think of it like this

A type hint is like a label on a storage box that says "screws only". It tells everyone what should go inside. The label does not stop someone from dropping in a sock.

Where the analogy stops being true. A paper label cannot be read by a program, but Python stores type hints and tools can read them and warn you. Python itself still does not check them.

What to know

Example

def double(n: int) -> int:
    return n * 2

names: list[str] = ["ann", "bo"]
counts: dict[str, int] = {"meeting_request": 3}
reply: str | None = None

print(double(4))
print(double("ab"))
print(double.__annotations__)
print(names, counts, reply)

It prints:

8
abab
{'n': <class 'int'>, 'return': <class 'int'>}
['ann', 'bo'] {'meeting_request': 3} None

Predict, then check

1. What does this print?

def shout(text: str) -> str:
    return text.upper()

print(shout("ok"))
Show the answer
OK

The argument matches the hint, and str.upper() returns the capital letters.

2. What does this print? (The hint says str.)

def label_len(label: str) -> int:
    return len(label)

print(label_len([1, 2, 3]))
Show the answer
3

The hint is not enforced. len() works on a list, so the call runs and returns 3.

3. What does this print?

def pick(label: str | None) -> str:
    return label or "unknown"

print(pick(None), pick("spam"))
Show the answer
unknown spam

str | None says the argument may be a string or None. With None, the expression label or "unknown" gives "unknown".

Try it

Write a function tag(label) with hints: label is a str or None, and it returns a str. Return the label in upper case, or "UNKNOWN" when label is None.

def tag(label):
    return label
Show a solution
def tag(label: str | None) -> str:
    if label is None:
        return "UNKNOWN"
    return label.upper()

Common mistake

Do not assume a hint checks anything when the program runs. double("ab") in the example has the wrong type and still returns a result. If you want a real check, write one (for example with isinstance or an exception).

In a small-language-model project

In an SLM project, hints such as list[Example] or str | None on your data functions tell you what each step expects. A type checker can then spot mistakes before you start a long training run.

Sources

Each quote below appears word for word on the cited page of the official Python documentation (version 3.12).

Step through this lesson in the Hi! Python desktop

← DataclassesExceptions →