Python type hints: are they checked at runtime?
posée 2 months ago306 vuesen
I added def greet(name: str) -> str: but calling greet(42) doesn't raise any error. What's the point of type hints then?
Diagnostic IA
Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.
1 réponse
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.
Connectez-vous pour dire si ça a marché.
Sign in and verify your email to post an answer.