Chapter 1: The Basics / Lesson 5

Type Hints and Annotations

6 min ยท The Basics

Type Hints in Python

Type hints (introduced in Python 3.5) allow you to specify the expected types of variables, function parameters, and return values. While Python is dynamically typed (types are determined at runtime), type hints add static type information that makes code more readable and helps catch errors early.

Type hints don't change how Python runs your code - they're completely optional. However, they provide valuable documentation and can be used by tools like mypy to check for type errors before running your code.

type_hints.py
# Variable type hints name: str = "Alice" age: int = 25 height: float = 5.6 is_active: bool = True # Type hints tell us what type each variable should be print(type(name)) # <class 'str'> print(type(age)) # <class 'int'>

Function Type Hints

Type hints are especially useful for functions. They document what types of arguments a function expects and what type it returns:

function_hints.py
# Function with type hints # Syntax: def function_name(param: type) -> return_type: def greet(name: str) -> str: return f"Hello, {name}!" # Multiple parameters with type hints def add(a: int, b: int) -> int: return a + b # Function that returns None (no return value) def display(message: str) -> None: print(message) print(greet("Bob")) # Hello, Bob! print(add(5, 3)) # 8 display("Hello")

Optional Types

When a value might be None, you can use Optional or the shorthand | syntax (Python 3.10+):

optional.py
from typing import Optional # A value that might be None username: Optional[str] = None username = "Alice" # Can also be a string # Python 3.10+ syntax (shorter) age: int | None = None # Function with optional parameter def greet(name: str, title: Optional[str] = None) -> str: if title: return f"Hello, {title} {name}!" return f"Hello, {name}!"

Common Type Hints

Here are the most commonly used type hints:

common_types.py
# Basic types name: str = "Alice" age: int = 25 price: float = 19.99 is_active: bool = True # Collections (we'll learn about these later) from typing import List, Dict, Tuple numbers: List[int] = [1, 2, 3] scores: Dict[str, int] = {"Alice": 95, "Bob": 87} coordinates: Tuple[float, float] = (10.5, 20.3)

Benefits of Type Hints

Type hints provide several advantages:

  • Documentation - They serve as inline documentation explaining what types are expected
  • IDE Support - IDEs can provide better autocomplete and error detection
  • Early Error Detection - Tools like mypy can catch type errors before runtime
  • Code Clarity - Makes code easier to understand for other developers
  • Refactoring - Makes it safer to refactor code

๐Ÿ“ Important Note

Type hints are optional and don't affect runtime behavior. Python won't throw an error if you pass the wrong type - they're primarily for documentation and static type checkers like mypy. This means you can gradually add type hints to existing code without breaking anything.

When to Use Type Hints

โœ… Use Type Hints When:

โ€ข Writing functions others will use (library code)

โ€ข Working on large projects with multiple developers

โ€ข You want better IDE support and autocomplete

โ€ข You want to catch errors early during development

๐Ÿ’ก Optional for Simple Scripts

For simple, personal scripts, type hints are optional. However, using them even in small programs helps you practice and makes code clearer.

๐ŸŽ‰

Lesson Complete!

Great work! Continue to the next lesson.

main.py
๐Ÿ“ค Output
Click "Run" to execute...