Defining Type Hints for Container Types
While defining type hints for basic data types (such as int
, float
, str
) is straightforward, working with container types (like lists, dictionaries, and sets) can be more complex. Python's type hint syntax provides several ways to annotate container types, allowing you to specify the types of the container's elements.
Annotating Lists
To define the type of elements in a list, you can use the List[T]
type hint, where T
represents the type of the list elements. For example:
from typing import List
def process_numbers(numbers: List[int]) -> List[int]:
return [num * 2 for num in numbers]
In this example, the numbers
parameter is annotated as a List[int]
, indicating that it should be a list of integers.
Annotating Dictionaries
For dictionaries, you can use the Dict[K, V]
type hint, where K
represents the type of the keys, and V
represents the type of the values. For example:
from typing import Dict
def get_student_info(student_id: int) -> Dict[str, int]:
student_info = {
"student_id": student_id,
"age": 20,
"grade": 85
}
return student_info
In this case, the return type of the get_student_info
function is annotated as Dict[str, int]
, indicating that the dictionary has string keys and integer values.
Annotating Sets
To annotate a set, you can use the Set[T]
type hint, where T
represents the type of the set elements. For example:
from typing import Set
def get_unique_numbers(numbers: List[int]) -> Set[int]:
return set(numbers)
Here, the return type of the get_unique_numbers
function is annotated as Set[int]
, meaning that it returns a set of integers.
Nested Container Types
You can also define type hints for nested container types, such as a list of dictionaries or a dictionary of lists. For example:
from typing import List, Dict
def process_student_data(student_data: List[Dict[str, int]]) -> Dict[str, List[int]]:
result = {}
for student in student_data:
for key, value in student.items():
if key not in result:
result[key] = []
result[key].append(value)
return result
In this example, the student_data
parameter is annotated as a List[Dict[str, int]]
, indicating that it is a list of dictionaries, where each dictionary has string keys and integer values. The return type is annotated as Dict[str, List[int]]
, meaning that the function returns a dictionary with string keys and lists of integers as values.
By understanding how to define type hints for container types, you can write more expressive and maintainable Python code, leveraging the benefits of static type checking and improved IDE support.