Category: python
Introduction to Type Hints
Published on 27 Oct 2026
Explanation
Type hints document expected types. Python generally does not enforce annotations at runtime automatically; type checkers and editors can use them.
Code:
def add(a: int, b: int) -> int:
return a + b
print(add(10, 20))
Explanation
Parameter and return annotations clarify a function's contract and improve editor support.
Code:
def format_user(name: str, age: int) -> str:
return f'{name} is {age} years old'
print(format_user('Arun', 25))
Explanation
Built-in generic types describe collection contents. Python 3.10+ supports unions such as str | None.
Code:
def find_user(user_id: int) -> dict[str, str] | None:
users = {1: {'name': 'Arun'}}
return users.get(user_id)
print(find_user(1))
Explanation
Type hints can describe class attributes and method signatures, helping readers and static analysis tools.
Code:
class Student:
def __init__(self, name: str, marks: float) -> None:
self.name = name
self.marks = marks
def passed(self) -> bool: return self.marks >= 35
print(Student('Arun', 80).passed())
Explanation
TypedDict describes expected dictionary keys to static type checkers. Annotations alone do not validate untrusted input at runtime.
Code:
from typing import TypedDict
class Student(TypedDict):
name: str
marks: int
def display(s: Student) -> str: return f"{s['name']}: {s['marks']}"
print(display({'name': 'Arun', 'marks': 90}))