Python Type Hints
Table of Contents
In the last lesson, we learned about Python Dataclasses. Now let us add type hints that make expected values clearer to developers and tools.
๐งฉ What Are Type Hints in Python?
Type hints are annotations that tell us what type a variable or function is expected to have. They do not change how Python runs the code. They are just hints for developers and tools.
We use a colon : after a variable name to add a type hint.
name: str = "Alex"age: int = 25For functions, we use -> to specify the return type.
def add(a: int, b: int) -> int: return a + b๐ฏ Why Do We Need Type Hints in Python?
Type hints make our code clearer. When we read a function, we know what types it expects and returns. That helps us avoid mistakes.
Type hints also help tools like IDEs and linters catch errors before we run the code. They can also be used to generate documentation.
โ๏ธ How to Use Type Hints in Python
We can add type hints to variables, function parameters, and return values.
def greet(name: str) -> str: return f"Hello, {name}"
result: str = greet("Alex")print(result)Output
Hello, AlexThe name: str means the parameter should be a string. The -> str means the function returns a string.
๐ง Type Hints for Collections in Python
We can use type hints for lists, dictionaries, and other collections.
from typing import List, Dict
def process(numbers: List[int]) -> int: return sum(numbers)
scores: Dict[str, int] = {"Alex": 85, "Sam": 92}print(process([1, 2, 3]))print(scores)Output
6{'Alex': 85, 'Sam': 92}In Python 3.9 and later, we can use built-in types directly.
def process(numbers: list[int]) -> int: return sum(numbers)That is cleaner.
๐ก Optional Types in Python
We can use Optional to indicate that a value can be None.
from typing import Optional
def find_user(user_id: int) -> Optional[str]: if user_id == 1: return "Alex" return None
print(find_user(1))print(find_user(2))Output
AlexNoneIn Python 3.10 and later, we can use str | None.
def find_user(user_id: int) -> str | None: ...๐ A Real-Life Example โ Type Hints in a Class
class Student: def __init__(self, name: str, age: int, grades: list[int]): self.name = name self.age = age self.grades = grades
def average(self) -> float: return sum(self.grades) / len(self.grades)
student = Student("Alex", 20, [85, 90, 78])print(student.average())Output
84.33333333333333That makes the class easier to understand.
๐ฆ Common Mistakes with Type Hints in Python
๐งช Mistake 1: Thinking type hints are enforced
def add(a: int, b: int) -> int: return a + b
print(add("5", "3"))Output
53Type hints do not enforce types. Python still runs the code. The hint is just a hint.
๐ Mistake 2: Forgetting to import from typing
def process(numbers: List[int]) -> int: ...This gives an error if List is not imported.
Fix:
from typing import ListOr use built-in list in Python 3.9+.
๐ Mistake 3: Using type hints for everything
Type hints are helpful but not required. Use them where they add clarity. Not every variable needs a type hint.
Next, we will learn about Python Named Tuples and access tuple values through readable field names.