I am not able to find a simple way how to initialize a Pydantic object from field values given by position (for example in a list instead of a dictionary) so I have written class method positional_fields()
to create the required dictionary from an iterable:
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)
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
Is there a more straightforward way of achieving this?
My method expects the __fields__
dictionary to have keys in the order the fields were defined in the class. I am not sure if this is guaranteed (assuming Python 3.6+).