Python如何为接收任意Pydantic schema/model的函数添加类型提示
任意Pydantic模型参数的类型注解方案
你可以根据自己的Pydantic版本和业务校验需求,选择以下两种写法:
方案1:直接绑定Pydantic基类(最常用)
直接用Pydantic所有模型的公共父类BaseModel做类型注解,所有你自定义的Pydantic schema都会自动符合这个类型要求:
from typing import Optional from pydantic import BaseModel # 导入你自己的密码上下文配置 from your_config_module import config def hash_password(password: str, schema: Optional[BaseModel] = None) -> str: if schema: del schema.password if hasattr(schema, 'password') else None return config.pwd_context.hash(password)
注:如果你同时用Pydantic v1和v2的兼容模式,把导入路径替换为
from pydantic.v1 import BaseModel即可。
方案2:结构类型注解(更贴合当前代码逻辑)
如果你的代码逻辑只要求传入的对象带有password属性,不强制必须是Pydantic模型,可以用Protocol定义结构子类型,类型检查会更灵活精准:
from typing import Optional, Protocol # 定义协议:只要包含password属性的对象都符合类型要求 class HasPassword(Protocol): password: str # 导入你自己的密码上下文配置 from your_config_module import config def hash_password(password: str, schema: Optional[HasPassword] = None) -> str: if schema: del schema.password if hasattr(schema, 'password') else None return config.pwd_context.hash(password)
内容的提问来源于stack exchange,提问作者salius
相关产品推荐
相关产品推荐

