大数据

python typing操作

test01.py

from typing import List, Dict, Tuple, Set

# List
cities: List[str | int] = ['济南', '青岛', 99]

# Dict
scores: Dict[str, int] = {"英语": 90, "数学": 100}

# Tuple
server: Tuple[str, int] = ('localhost', 80)

# Set
key: Set[str] = {"1", 2}

test02.py

from typing import Union, Optional, Any, List, TypeAlias

# Union类型可以在定义变量时指定多种数据类型
person: Union[str, int] = "张三"
# 等价
person2: str | int = "张三"

# Optional类型是可选类型 代表变量值可以为None
# 用Optional
x: Optional[str] = "x"
# 用Union
x2: Union[str, None] = "x"
# 用 |
x3: str | None = "x"

# Any类型代表该变量赋值所有的值都是允许的,如果没有指定类型,默认就是Any类型
a: Any = "x"

StrList: TypeAlias = List[str]


def get_urls(urls: StrList):
    pass