Python Type Hints

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 = 25

For 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, Alex

The 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

Alex
None

In 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.33333333333333

That 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

53

Type 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 List

Or 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.