相关疑难解决方法(0)

如何从位置而不是名称给出的字段值初始化 Pydantic 对象?

我无法找到一种简单的方法来根据位置给定的字段值(例如在列表而不是字典中)初始化 Pydantic 对象,因此我编写了类方法positional_fields()来从可迭代创建所需的字典:

from typing import Optional, Iterable, Any, Dict
from pydantic import BaseModel


class StaticRoute(BaseModel):
    if_name: str
    dest_ip: str
    mask: str
    gateway_ip: str
    distance: Optional[int]
    
    @classmethod
    def positional_fields(cls, values: Iterable) -> Dict[str, Any]:
        return dict(zip(cls.__fields__, values))


input_lines = """
  route ab 10.0.0.0 255.0.0.0 10.220.196.23 1
  route gh 10.0.2.61 255.255.255.255 10.220.198.38 1
""".splitlines()

for line in input_lines:
    words = line.split()
    if words and words[0] == 'route':
        sroute = StaticRoute(**StaticRoute.positional_fields(words[1:]))
        print(sroute)
Run Code Online (Sandbox Code Playgroud)
if_name='ab' dest_ip='10.0.0.0' mask='255.0.0.0' gateway_ip='10.220.196.23' distance=1
if_name='gh' dest_ip='10.0.2.61' mask='255.255.255.255' …
Run Code Online (Sandbox Code Playgroud)

python iterable pydantic

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

iterable ×1

pydantic ×1

python ×1