Type hints and annotations are features in Python that allow developers to indicate the expected data types of function arguments, return values, and variables. They improve code readability and help tools like linters and IDEs catch type-related errors during development.
You can specify the type of a function argument by using a colon (:
) followed by the type.
def greet(name: str):
print(f"Hello, {name}!")
Use ->
to specify the return type of a function.
def add(a: int, b: int) -> int:
return a + b
def concat_strings(a: str, b: str) -> str:
return a + b
Type hints are optional and do not enforce type checking at runtime. They are used for static analysis and better code clarity.
typing
ModuleThe typing
module provides additional tools for complex type annotations.
from typing import List
def sum_list(numbers: List[int]) -> int:
return sum(numbers)
from typing import Tuple
def get_coordinates() -> Tuple[int, int]:
return (10, 20)
from typing import Dict
def count_fruits() -> Dict[str, int]:
return {"apple": 10, "banana": 20}
from typing import Union
def process_value(value: Union[int, str]) -> str:
return str(value)
from typing import Optional
def find_item(item_id: int) -> Optional[str]:
if item_id == 1:
return "Item Found"
return None
Using typing
is essential for complex type definitions, especially when working with collections or mixed types.
Create aliases for commonly used type definitions to improve readability.
from typing import List
# Define a type alias
UserIDList = List[int]
def get_user_ids() -> UserIDList:
return [1, 2, 3, 4]
project/ ├── main.py └── utils.py
Objective: Add type hints to the following functions.
def multiply(a, b):
return a * b
def multiply(a: int, b: int) -> int:
return a * b
Define a function that takes a list of strings and returns a dictionary of string counts.
from typing import List, Dict
def count_words(words: List[str]) -> Dict[str, int]:
result = {}
for word in words:
result[word] = result.get(word, 0) + 1
return result
Consider using type hints in all functions for better clarity and integration with modern IDEs and tools.