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

pab*_*ouk 5 python iterable 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' gateway_ip='10.220.198.38' distance=1
Run Code Online (Sandbox Code Playgroud)

有没有更直接的方法来实现这一目标?

我的方法期望__fields__字典的键按照类中定义字段的顺序排列。我不确定这是否得到保证(假设 Python 3.6+)。

fun*_*man 2

使用数据类怎么样?就像是:

from typing import Optional

from pydantic.dataclasses import dataclass


@dataclass
class StaticRoute:
    if_name: str
    dest_ip: str
    mask: str
    gateway_ip: str
    distance: Optional[int]


words = "route if_name dest_ip mask gateway_ip 10".split()
print(StaticRoute(*words[1:])

# StaticRoute(if_name='if_name', dest_ip='dest_ip', mask='mask', gateway_ip='gateway_ip', distance=10)
Run Code Online (Sandbox Code Playgroud)