Type hints are annotations that describe the kind of value a function expects or returns.
Python still runs dynamically, but type hints help editors, reviewers, and static checkers catch mistakes earlier.
Use type hints to make function boundaries clear, not to make every tiny variable look complicated.
Function annotations show parameter and return types directly in the function definition.
def format_total(amount: float, currency: str = "INR") -> str:
return f"{currency} {amount:.2f}"
print(format_total(499.5))
INR 499.50
The hints say amount should be a float, currency should be text, and the result should be text.
Collection hints explain what kind of values a list, tuple, set, or dictionary should contain.
def total_marks(scores: dict[str, int]) -> int:
return sum(scores.values())
marks = {"math": 88, "science": 91}
print(total_marks(marks))
179
The function expects a dictionary where subject names are strings and marks are integers.
Some values can be present or missing. Type hints can show that a value may be None.
def display_email(email: str | None) -> str:
if email is None:
return "No email added"
return email.lower()
print(display_email(None))
No email added
The hint makes it obvious that None is allowed and must be handled.
A type alias gives a readable name to a repeated or complex type shape.
A Protocol describes the operations a value must support without requiring inheritance from one base class. Static checkers can accept any object with the compatible members, which matches Python duck typing while making the expected behavior visible.
from typing import Protocol
class Closable(Protocol):
def close(self) -> None: ...
def finish(resource: Closable) -> None:
resource.close()
The annotation supports static checking; add @runtime_checkable only when an actual isinstance() check is required.
A type variable preserves a relationship between input and output types. It is more precise than returning object or Any because the checker can infer the result from the supplied collection.
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T:
if not items:
raise ValueError("items must not be empty")
return items[0]
print(first([10, 20, 30]))
10
Try this next
0 of 3 completed
No. Python still runs dynamically. Type hints mainly help tools, editors, documentation, and code review.
No. Start with function parameters, returns, and confusing data structures. Obvious local variables rarely need hints.
It means the value can be a string or None, so your code should handle both cases.
Explore 500+ free tutorials across 20+ languages and frameworks.