You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从字符串创建Pydantic枚举类NoteTemplate

用字符串创建Pydantic枚举类实例

你定义的NoteTemplate枚举类本身就支持通过字符串直接创建实例——因为它同时继承了str和Enum,枚举成员的值就是对应的字符串,直接传入匹配的字符串即可完成初始化。

原枚举类代码

from pydantic import BaseModel
from uuid import UUID
from enum import Enum
from datetime import datetime


class NoteTemplate(str, Enum):
    general_practitioner = "general_practitioner"
    cardiologist = "cardiologist"
    soap = "soap"
    consultation_report = "consultation_report"
    plastic_surgeon = "plastic_surgeon"
    orthopedist = "orthopedist"

使用示例

直接将目标字符串传入枚举类构造函数即可:

# 创建全科医生模板实例
gp_template = NoteTemplate("general_practitioner")
print(gp_template)          # 输出: NoteTemplate.general_practitioner
print(gp_template.value)    # 输出: general_practitioner

注意事项

  • 传入的字符串必须和枚举成员的值完全匹配(大小写、下划线都要一致),否则会抛出ValueError:
try:
    # 传入无效值会触发错误
    invalid_template = NoteTemplate("wrong_value")
except ValueError as e:
    print(e)  # 输出: 'wrong_value' is not a valid NoteTemplate

内容的提问来源于stack exchange,提问作者p.magalhaes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 22:59:50