Python Advanced
Python Type Hints
Type hints let you document the expected data type of variables and function arguments, making your Python code easier to read and catch bugs before running it.
Basic Annotations
Python is dynamically typed, but you can add optional type hints using a colon after a variable name, and an arrow before a function's return type. Python does not enforce these at runtime — they are hints for humans and tools.
name: str = "Aarav"
age: int = 21
gpa: float = 8.7
def greet(person: str) -> str:
return f"Hello, {person}!"Using the typing Module
For more complex data types like lists, dictionaries and optional values, import helpers from the typing module. These describe what the collection contains, not just its outer type.
from typing import List, Dict, Optional
def average(scores: List[int]) -> float:
return sum(scores) / len(scores)
def user_ages(users: Dict[str, int]) -> None:
for name, age in users.items():
print(name, age)
def find_user(user_id: int) -> Optional[str]:
users = {1: "Aarav", 2: "Priya"}
return users.get(user_id)Optional[str] means the value is either a str or None — it is shorthand for Union[str, None]. In Python 3.10+ you can also write str | None.
Modern Syntax (Python 3.9+)
Since Python 3.9, you can use built-in list and dict directly as generics instead of importing List and Dict, making code cleaner.
def average(scores: list[int]) -> float:
return sum(scores) / len(scores)
def find_user(user_id: int) -> str | None:
...Checking Types with mypy
Type hints alone don't stop your program from running with wrong types. A separate tool called mypy reads your annotations and reports mismatches before you even run the code, catching bugs early during development.
pip install mypy
mypy my_script.pyType hints are optional and completely ignored by the Python interpreter at runtime — they only help readers, IDEs, and tools like mypy.
| Hint | Meaning |
|---|---|
| x: int | x should be an integer |
| x: List[str] | x should be a list of strings |
| x: Dict[str, int] | x maps string keys to int values |
| x: Optional[str] | x is a str or None |
