Python type hints: are they checked at runtime?

poze 2 months ago300 gadeen

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?

Dyagnostik IA

Se IA ki fè l. Se pa yon repons — kominote a anba a konfime oswa korije l. Toujou verifye anvan ou fye l.

poze 2 months ago

1 Repons

9
✓
✓ Repons yo aksepte

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.

Konekte pou di lòt moun si li te mache.

answered 2 months ago

Sign in and verify your email to post an answer.