Introduction 🌟
Type Hints (also called type annotations) allow you to explicitly specify the expected data types of variables, function arguments, and return values. They improve readability, catch bugs early, and help tools like IDEs & linters understand your code better.
Note
💡 They are checked by tools (mypy, pyright, IDEs)
💡 Introduced in Python 3.5 and improved in later versions
1. Type Hints for Variables 🧱
var_annotations.py
name: str = "Sathish"
age: int = 25
price: float = 99.99
active: bool = True✔ Improves code clarity
2. Type Hints for Functions 🧠
func_annotations.py
def add(a: int, b: int) -> int:
return a + b✔ a: int → argument annotation
✔ -> int → return type annotation
3. Type Hints for Multiple Return Types 🔄
union_example.py
from typing import Union
def parse(value: str) -> Union[int, float]:
if "." in value:
return float(value)
return int(value)4. Optional Types (value may be None) ❓
optional.py
from typing import Optional
def get_user(id: int) -> Optional[str]:
if id == 1:
return "Sathish"
return None✔ Optional[str] == Union[str, None]
5. Type Hints for Lists, Dicts, Sets, Tuples 📦
collections_typing.py
from typing import List, Dict, Set, Tuple
nums: List[int] = [1, 2, 3]
user: Dict[str, int] = {"age": 25}
unique: Set[str] = {"a", "b"}
point: Tuple[int, int] = (10, 20)6. Modern Syntax (PEP 585) 🎯
Python 3.9+ allows built-in generics:
pep585.py
nums: list[int] = [1, 2, 3]
user: dict[str, int] = {"age": 25}
matrix: list[list[int]] = [[1,2], [3,4]]✔ Cleaner & recommended
7. Callable Types (Functions as Arguments) 🛠️
callable_example.py
from typing import Callable
def operate(func: Callable[[int, int], int], x: int, y: int) -> int:
return func(x, y)8. Annotating Classes & Methods 🏗️
class_annotations.py
class User:
name: str
age: int
def greeting(self) -> str:
return f"Hello {self.name}"9. Forward References (Type Appears Later) 🔁
forward_ref.py
from __future__ import annotations
class A:
def connect(self, other: A) -> None:
pass10. Type Aliases 🎭
type_alias.py
UserId = int
def get_user(id: UserId) -> str:
return "User"✔ Makes code more expressive
11. Literal Types (Specific Allowed Values) 🎯
literal_example.py
from typing import Literal
def move(direction: Literal["up", "down", "left", "right"]) -> None:
print(direction)✔ Useful for enums & restricted values
12. TypedDict — Dictionary with Typed Keys 🧾
typed_dict.py
from typing import TypedDict
class User(TypedDict):
name: str
age: int
user: User = {"name": "Sathish", "age": 25}13. Dataclasses + Type Hints 🏷️
dataclass_example.py
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int14. Generic Types (Advanced) 🔧
generics.py
from typing import TypeVar, Generic
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value
int_box = Box
str_box = Box[str]("hello")✔ Enables creating reusable, typed classes
15. Enforcing Types with mypy (Static Checker) 📌
Run:
Code Snippet
mypy script.py✔ Reports type errors during development
16. Real-World Example — E-commerce Cart 🛒
ecommerce_example.py
from typing import List
def calculate_total(prices: List[float]) -> float:
return sum(prices)
print(calculate_total([10.5, 20.0, 5.5]))17. Real-World Example — API Response Types 🌐
api_example.py
from typing import Dict, Any
def get_response() -> Dict[str, Any]:
return {"status": 200, "data": [1, 2, 3]}Type Hint Cheat Sheet 📘
| Feature | Example |
|---|---|
| Simple Types | x: int |
| Function | def f(a: int) -> str |
| Union | Union[int, str] |
| Optional | Optional[str] |
| Collections | list[int], dict[str, int] |
| Callable | Callable[[int], str] |
| Literal | Literal["yes", "no"] |
| TypedDict | class User(TypedDict) |
| Generics | Generic[T] |
Best Practices 💡
- ✔ Use type hints everywhere in large projects
- ✔ Prefer built-in generics like list[int] (Python 3.9+)
- ✔ Use mypy for type checking
- ✔ Use Optional when values may be None
- ✔ Use type aliases for readability
- ✔ Avoid overcomplicating small scripts with excessive types
Conclusion 🎉
You now fully understand Type Hints in Python! Want the next topic? Try Dataclasses, Enums, Protocols, or mypy Guide. Just tell me! 😊