How can I unpack a Pydantic BaseModel into kwargs?
Asked Answered
D

1

6

I am trying to make a function that takes a pydantic BaseModel as an input to run another function. I need to unpack the BaseModel into kwargs. I tried doing this:

def run_routing_from_job(job):
    return run_routing(
        job.inputs.input_file,
        **job.inputs.config.dict()
    )

where job is of the format

class Job(BaseModel):
    client_info: ClientInfo  # Another BaseModel
    inputs: RoutingJobInputs  # Another BaseModel
    uid: UUID = Field(default_factory=uuid4)
    status: str = "job_queued"
    result: int = None

However, doing .dict() parses all of the items recursively into a dictionary format. I want to keep the client_info and inputs as a BaseModel class, not convert it into a dictionary.

I could make a way to do it, but I can't find a clean way to do it.

Daube answered 1/12, 2021 at 12:43 Comment(2)
Why not just use a job: Job argument instead of **kwargs?Afore
@HernánAlarcón I was using someone elses code, I'm going to go back and modify it to accept job instead, but for now I just wanted to unpack the basemodelDaube
D
3

I worked it out, just replace .dict() with __dict__

def run_routing_from_job(job):
    return run_routing(
        job.inputs.input_file,
        **job.inputs.config.__dict__
    )
Daube answered 1/12, 2021 at 12:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.