-
I have a solution (see code below) to a problem, but I'm thinking there is perhaps a better way? I've half-contemplated using dict, or Literal, but solution below uses Enum. The problem: I have a large amount of fields that are all of key-value pairs (must be named For this small example, the goal is to get it to dictionary of type:
(If I have the dict above, it's trivial to then use
) CodeThe code below gives the desired output, but to get there, I have to define custom from enum import Enum
import xmltodict
from polyfactory.factories.pydantic_factory import ModelFactory
from pydantic import BaseModel, Field
from pprint import pprint
class MyPairs(BaseModel):
"""For holding key-value pairs: V (value) + N (name)"""
V: str = Field(alias="@V", description="Value")
N: str = Field(alias="@N", description="Name")
class Config:
"""Assign values using field name, rather than alias names"""
populate_by_name = True
class Sex(Enum):
Unknown = 0
Man = 1
Woman = 2
Not_applicable = 9
class Compression(Enum):
Deflate = "DF"
Gzip = "GZ"
Compress = "Z"
class Person(BaseModel):
name: str
sex: MyPairs # ideally specify it takes values defined in "Sex" Enum
compression: MyPairs # ideally specify it takes values defined in "Compression" Enum
class PersonFactory(ModelFactory[Person]):
@classmethod
def sex(cls) -> MyPairs:
# Need to unpack the enum, to populate the MyPairs object
e = cls.__random__.choice(list(Sex))
return MyPairs(V=str(e.value), N=e.name)
@classmethod
def compression(cls) -> MyPairs:
e = cls.__random__.choice(list(Compression))
return MyPairs(V=e.value, N=e.name)
# The "Person's" Pet will have name that's random string, rather than generated by "Faker" module.
fake_person = PersonFactory.build()
print("\nPERSON:")
print(fake_person)
print("\n")
d_fake = {"root": fake_person.dict(by_alias=True)}
pprint(d_fake)
xml_fake = xmltodict.unparse(d_fake, pretty=True).replace("\t", " ")
print(xml_fake) AlternativeWhy not use the Enum directly, instead of unpacking it in a class Person(BaseModel):
name: str
sex: MyPairs
compression: Compression Well, then output is:
Rather then the desired
I've experimented with overloading various dunder methods of the Possibly I should overload the function that converts the pydantic data model to dict? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I think this is expected behaviour from polyfactory. For first idea, without type information on specific type so need to specify this explicitly. For alternative, assuming pydantic 2 something like this might work. Note this is incomplete if you want to load data
|
Beta Was this translation helpful? Give feedback.
I think this is expected behaviour from polyfactory. For first idea, without type information on specific type so need to specify this explicitly.
For alternative, assuming pydantic 2 something like this might work. Note this is incomplete if you want to load data