Type Hint
In one line
Type hints are optional annotations that declare the expected types of variables, parameters, and return values.
In simple words
Type hints (type annotations) are optional declarations that specify the expected types of function parameters, return values, and variables. They were introduced in Python 3.5 and do not affect runtime behavior — Python does not enforce them.
Type hints improve code readability and enable static type checking with tools like mypy, pyright, and IDE integrations. They catch type-related bugs before running the code, similar to TypeScript's type system.
Syntax: def func(x: int, y: str) -> bool:. For variables: age: int = 30. Use the typing module for complex types like List[int], Dict[str, int], Optional[str], Union[int, str].
Example
from typing import List, Dict, Optional
def greet(name: str, times: int = 1) -> str:
return (f"Hello, {name}! " * times).strip()
def find_first(items: List[int], target: int) -> Optional[int]:
"""Return index of target, or None if not found."""
for i, item in enumerate(items):
if item == target:
return i
return None
# Type hints are not enforced at runtime
print(greet("Alice", 3)) # Hello, Alice! Hello, Alice! Hello, Alice!Type hints annotate types for documentation and static checking. They are not enforced at runtime.
Common confusions
Confused with: type declaration
The difference: Type hints in Python are annotations — they document expected types but are NOT enforced at runtime. Type declarations in statically typed languages (Java, C) are enforced by the compiler. Python type hints are checked by external tools like mypy, not by Python itself.
Related terms
Related Resources
Related Lessons
- Type Hints
Type hints.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.