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.
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
- Annotate a variable with a colon: names: list[str].
- Annotate a function with parameter hints and an arrow for the return value: def double(n: int) -> int.
- The Python runtime does not enforce function and variable type annotations.
- The example proves it: double("ab") runs fine and returns "abab".
- Hints can be written as list[str], dict[str, int] and str | None.
- Python keeps the function hints in double.__annotations__, where tools can read them.
- The typing docs say third party tools such as type checkers can use annotations.
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
OKThe 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
3The 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 spamstr | 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).
The Python runtime does not enforce function and variable type annotations.
docs.python.org/3.12/library/typing.html — The runtime does not enforce type annotations.They can be used by third party tools such as type checkers
docs.python.org/3.12/library/typing.html — Annotations can be used by third party tools such as type checkers.Union[X, Y] is equivalent to X | Y and means either X or Y.
docs.python.org/3.12/library/typing.html — X | Y is a shorthand for a union meaning either X or Y.