After a few days of Python, most Java developers ask the same question: “where did the types go?” Then they open a modern codebase and find them everywhere:
def embed(text: str, dims: int = 1024) -> list[float]:
...
These are type hints. They look like Java types written backwards, and they help in the same ways: your editor autocompletes better, tools catch mistakes, and readers know what goes in and out. But there’s one big difference you have to internalise: Python does not check them when your program runs.
This is part 9 of Python for Java Developers. Part 8 covered comprehensions.
The syntax: the type goes after the name
public List<Double> embed(String text, int dims) { ... }
private final Map<String, Integer> counts = new HashMap<>();def embed(text: str, dims: int = 1024) -> list[float]:
...
counts: dict[str, int] = {}A colon after each parameter, then the type. -> type after the parameter list is the return type. Variables can carry a hint too: name: type = value.
The hints you’ll meet, mapped to Java
| Python hint | Means | Java |
|---|---|---|
str, int, float, bool |
Basic types | String, int/long, double, boolean |
list[str] |
A list of strings | List<String> |
dict[str, int] |
Keys str, values int |
Map<String, Integer> |
set[str] |
A set of strings | Set<String> |
tuple[int, int] |
Exactly two ints | a small record |
tuple[str, ...] |
Any number of strings | String[] (immutable) |
str | None |
A string or None |
Optional<String> / nullable String |
Optional[str] |
Older spelling of str | None |
same |
int | str |
Either type | (no direct equivalent) |
Any |
Anything, unchecked | Object with casts |
Callable[[str], int] |
A function from str to int |
Function<String, Integer> |
Literal["low", "high"] |
Only these exact values | an enum |
Iterable[str] |
Anything you can loop over | Iterable<String> |
Older code imports List, Dict and Optional from typing with capital letters. Since Python 3.9 the built-in names work directly (list[str]), and since 3.10 you can write str | None.
Hints are not enforced at runtime
This is the part that surprises Java developers:
def double(n: int) -> int:
return n * 2
double("ha") # returns "haha". No error.
Python reads the hints and stores them, but it runs your code exactly as if they weren’t there. A hint that says int does not stop a str from arriving.
Getting compiler-like checks: mypy and pyright
To get what javac gives you, run a type checker before you run the code:
uv add --dev mypy
uv run mypy app/
app/main.py:4: error: Argument 1 to "double" has incompatible type "str"; expected "int"
The two you’ll see are mypy (the original) and pyright (from Microsoft, which powers VS Code’s Python extension, Pylance). Both read your hints and report mismatches, missing None checks and wrong return types. Put one in CI and you get most of the safety you’re used to.
Only code with hints gets checked, so you can add them gradually, starting with function signatures.
Generics
Writing your own generic function used to need a TypeVar. Python 3.12 added a syntax that looks familiar:
static <T> T first(List<T> items) {
return items.get(0);
}def first[T](items: list[T]) -> T: # Python 3.12+
return items[0]
# older style, still common:
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T:
return items[0]In application code you’ll rarely need your own generics. Using list[str] and dict[str, int] covers most of it.
Protocol: an interface without implements
Java classes must say implements Comparable. Python uses duck typing: if an object has the right methods, it fits. A Protocol lets you write that down so the type checker can verify it:
from typing import Protocol
class Embedder(Protocol):
def embed(self, text: str) -> list[float]: ...
class OpenSourceEmbedder: # no "implements" anywhere
def embed(self, text: str) -> list[float]:
...
def index(docs: list[str], embedder: Embedder) -> None:
...
index(docs, OpenSourceEmbedder()) # type checker: OK, it has embed()
It’s like a Java interface that classes satisfy just by having the right methods.
Why AI code cares so much about hints
In plain Python, hints are documentation that tools check. In the libraries AI apps are built on, hints become behaviour. These libraries read your hints at runtime and act on them:
- Pydantic reads the hints on a model to validate and convert data.
priority: intturns"2"into2and rejects"high". - FastAPI reads the hints on an endpoint to parse the request, validate it, and generate the API docs.
- Agent frameworks read a function’s hints and docstring to describe it to the model as a tool.
from typing import Literal
def get_weather(city: str, unit: Literal["C", "F"] = "C") -> str:
"""Get the current weather for a city."""
...
From this, a framework can build a JSON schema for the model: city is a required string, unit must be "C" or "F", and the docstring explains what the tool does. The model reads that schema to decide when and how to call your function. Wrong hints mean wrong tool calls.
Traps for Java developers
- Trusting hints at the edges. Data from users, files, APIs and LLMs can be anything, whatever your hints say. Validate it with Pydantic.
Anyeverywhere. It switches checking off. It’s the Python version of casting everything toObject.- Forgetting
| None.def find(id: str) -> User:that can returnNoneshould say-> User | None. A type checker then makes callers handle the missing case, like Java’sOptional. - Expecting overloading by type. Hints don’t create overloads. One name is still one function.
Key takeaways
- Write
name: typeand-> return_type. The type goes after the name. list[str],dict[str, int],str | NoneandCallable[[str], int]map to Java’s generics,OptionalandFunction.- Python never enforces hints at runtime. Run mypy or pyright to check them, ideally in CI.
Protocoldescribes an interface that classes satisfy withoutimplements.- Pydantic, FastAPI and agent frameworks read hints and docstrings to validate data and describe tools.
Frequently asked questions
Are Python type hints enforced?
Not by Python itself. The interpreter ignores them when running your code. Type checkers like mypy and pyright enforce them before you run, and libraries like Pydantic and FastAPI use them to validate data at runtime.
What is the Python equivalent of Java’s Optional?
The hint str | None (or Optional[str] in older code). It’s only a hint: the value is either a string or None, and a type checker will insist that callers check for None before using it.
Should I use mypy or pyright?
Either works. Pyright is fast and powers VS Code’s Python support, so you may already see its errors in your editor. Mypy is the long-standing standard and is common in CI. Many teams use the one their editor already runs.
Does Python have generics like Java?
Yes, as hints. list[str] and dict[str, int] are generic types, and Python 3.12 lets you write generic functions and classes with def first[T](items: list[T]) -> T. As with all hints, they’re checked by tools, not at runtime.
Do I need type hints in Python?
They’re optional, but recommended for anything beyond a small script. They make code easier to read, let tools catch mistakes early, and are required by libraries like Pydantic and FastAPI to work at all.
Next in the series: Python decorators vs Java annotations, the @ that looks familiar and works completely differently.
Comments