logo

Python 类型提示简介

王哲峰 / 2022-12-01


目录

动机

类型提示

def get_full_name(first_name, last_name):
    full_name = first_name.title() + " " + last_name.title()
    return full_name

print(get_full_name("john", "doe"))
def get_full_name(first_name: str, last_name: str):
    full_name = first_name.title() + " " + last_name.title()
    return full_name

print(get_full_name("john", "doe"))

错误检查

def get_name_with_age(name: str, age: int):
    name_with_age = name + "is this old:" + str(age)
    return name_with_age

声明类型

简单类型

def get_items(item_a: str, item_b: int, item_c: float, item_d: bool, item_e: bytes):
    return item_a, item_b, item_c, item_d, item_e

嵌套类型

使用 typing 标准库来声明这些类型以及子类型

List

示例

from typing import List

def process_items(items: List[str]):
    for item in items:
        print(item)

Tuple 和 Set

示例

from typing import Tuple, Set

def process_items(items_t: Tuple[int, int, str], items_s: Set[bytes]):
    return items_t, items_s

Dict

示例

from typing import Dict

def process_items(prices: Dict[str, float]):
    for item_name, item_price in prices.items():
        print(item_name)
        print(item_price)

类作为类型

示例

class Person:
    def __init__(self, name: str):
        self.name = name

def get_person_name(one_person: Person):
    return one_person.name

Pydantic 模型

示例

class Person:
def __init__(self, name: str):
    self.name = name

def get_person_name(one_person: Person):
    return one_person.name

FastAPI 中的类型提示

使用 FastAPI 时用类型提示声明参数可以获得

pydantic

pydantic 示例

from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel
from pydantic import ValidationError


class User(BaseModel):
    id: int
    name = "John Doe"
    singnup_ts: Optional[datetime] = None
    friends: List[int] = []

external_data = {
    "id": "123",
    "singnup_ts": "2019-06-01 12:22",
    "friends": [1, 2, "3"],
}
user = User(**external_data)
print(user.id)
print(repr(user.singnup_ts))
print(user.friends)
print(user.dict())

try:
    User(signup_ts = "broken", friends = [1, 2, "not number"])
except ValidationError as e:
    print(e.json())

pydantic 特性

pydantic 安装

$ pip install pydantic
$ pip install "pydantic[email]"
$ pip install "pydantic[dotenv]"
$ pip install "pydantic[email,dotenv]"
$ pip install email-validation
$ pip install .
$ codna install pydantic -c conda-forge
$ pip install git+git://github.com/samuelcolvin/pydantic@master#egg=pydantic
# or with extras
$ pip install git+git://github.com/samuelcolvin/pydantic@master#egg=pydantic[email,dotenv]

pydantic 使用

Models