Python type hints: are they checked at runtime?

asked 2 months ago302 viewsen

7

I added def greet(name: str) -> str: but calling greet(42) doesn't raise any error. What's the point of type hints then?

AI diagnosis

AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.

asked 2 months ago

1 Answer

9
✓
✓ Accepted answer

Correct: Python does not enforce type hints at runtime. They're metadata for:

1. Static type checkers (mypy, pyright, the one built into VS Code/Pylance) that catch greet(42) *before* you run the code. 2. Editor features: autocomplete, go-to-definition, refactoring. 3. Libraries that read them at runtime on purpose: Pydantic, FastAPI and dataclasses use them for validation and serialization.

from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int

User(name="Ruth", age="not a number")  # raises ValidationError

Add mypy --strict or pyright to CI to get real value from the hints.

Sign in to tell others whether this worked.

answered 2 months ago

Sign in and verify your email to post an answer.