欢迎访问宙启技术站
智能推送

typing模块中常用的容器类型注解

发布时间:2024-01-13 19:31:48

typing模块中,常用的容器类型注解包括ListTupleSetDictUnion,它们可以用于指定函数参数或返回值的类型。下面是它们的使用示例。

1. List

List用于表示一个可变的有序列表,可以包含不同类型的元素。

from typing import List

def calculate_average(numbers: List[int]) -> float:
    return sum(numbers) / len(numbers)

numbers = [1, 2, 3, 4, 5]
average = calculate_average(numbers)
print(average)  # Output: 3.0

2. Tuple

Tuple用于表示一个不可变的有序序列,可以包含不同类型的元素。

from typing import Tuple

def get_name_info(name: Tuple[str, str, int]) -> str:
    first_name, last_name, age = name
    return f"The name is {last_name}, {first_name}, and the age is {age}."

name_tuple = ("John", "Doe", 25)
info = get_name_info(name_tuple)
print(info)  # Output: The name is Doe, John, and the age is 25.

3. Set

Set用于表示一个无序、 的元素集合,其中的元素可以是不同类型的。

from typing import Set

def get_unique_elements(numbers: Set[int]) -> Set[int]:
    return numbers

number_set = {1, 2, 3, 4, 5, 5}  # Note that 5 is repeated
unique_numbers = get_unique_elements(number_set)
print(unique_numbers)  # Output: {1, 2, 3, 4, 5}

4. Dict

Dict用于表示一个由键值对组成的字典,其中的键和值可以是不同类型的。

from typing import Dict

def get_person_info(person: Dict[str, str]) -> str:
    name = person["name"]
    age = person["age"]
    return f"The person's name is {name} and the age is {age}."

person_dict = {"name": "John Doe", "age": "25"}
info = get_person_info(person_dict)
print(info)  # Output: The person's name is John Doe and the age is 25.

5. Union

Union用于指定多种可能的类型。

from typing import Union

def divide(numerator: int, denominator: int) -> Union[int, float]:
    if denominator != 0:
        return numerator / denominator
    else:
        return "Invalid denominator"

result = divide(10, 2)
print(result)  # Output: 5.0

result = divide(10, 0)
print(result)  # Output: Invalid denominator

通过使用这些容器类型注解,可以提高代码的可读性和可维护性,同时还可以在静态类型检查工具、IDE和文档生成工具中使用它们来提供更好的代码提示和文档说明。