Python Types for Python Beginners
A beginner‑friendly guide to adding type hints in Python.
Note: This tutorial assumes you understand some basic Python syntax, but are new to type hints. To learn more about Python, see the Python Tutorial and Getting Started Guide
1. What is a Type Hint in Python?
A type hint in Python is a way to indicate the expected data type of a variable, function parameter, or return value. It's a hint to other developers (and to tools like type checkers and IDEs) about what type of data should be used with a particular piece of code.
Type hints are not enforced at runtime by Python itself, but they can be used by third-party tools (like Pyrefly) to catch type-related errors before your code runs. They also serve as documentation, making it easier for others to understand how to use your code. Here's an example of a simple function with type hints:
def greet(name: str) -> None:
print(f"Hello, {name}!")
2. Why Bother with Type Hints?
Python is a dynamically typed language, which means you can write code without declaring types. However, this can lead to bugs or ambiguity in your code.
TL;DR
- Catch bugs before running the code.
- Improve editor autocomplete & refactors.
- Turn your code into living documentation.
3. Primitive Types
Since Python 3.9 you can use all the primitive types directly as annotations.
You can also specify a parameter as optional by using Optional
type, or now with the | None
syntax.
4. Collections
Syntax Examples
- List of numbers
list[int] scores: list[int] = [98, 87, 91]
- Tuple of two floats
tuple[float, float] point: tuple[float, float] = (3.0, 4.0)
- Dict of str -> int
dict[str, int] inventory: dict[str, int] = {"apples": 5}
- Set of strings
set[str] authors: set[str] = {"Bob", "Eve"}
Since Python 3.9 you can subscript built‑ins directly—no need for from typing import List
.
5. Functions
Default values keep their annotation:
Variable‑length arguments:
5. Get Type Hint Signals Directly in Your Editor
You can download the Pyrefly extension for VSCode to get type hint signals directly in your IDE.
Next, install Pyrefly and check some code:
# Fast, zero‑config
pip install pyrefly
pyrefly check ./my_sample.py
# Check you whole project
pyrefly check my_project/
Create a pyrefly.toml to configure your project for Pyrefly. Instructions here.
6. Next Steps
- Install the Pyrefly extension and require it in your project.
- Annotate one small file in your project.
- Fix the first few warnings—don’t chase perfection yet.
- Increase coverage gradually; enjoy calmer coding.
Happy hacking 🐍✨