0

I have a class where I want to add a from_config class method to use a Pydantic BaseModel

an example would be

class Config(BaseModel):
    name: str = "Tom"
    id: int = 1

class User:

    def __init__(self, name, id):
        self.name = name
        self.id = id

    @classmethod
    def from_config(cls, config):
         return cls(name=config.name, id=config.id)

How can I change this so that the from_config uses unpacking to create the class? for instance, something like

    @classmethod
    def from_config(cls, config):
         return cls(*config)

This isn't working because it is unpacking a tuple from the config basemodel

EDIT:

This works:

class Config(BaseModel):
    name: str = "Tom"
    id: int = 1

class User:

    def __init__(self, *, name, id):
        self.name = name
        self.id = id

    @classmethod
    def from_config(cls, config):
         return cls(**config.dict())
Tom McLean
  • 5,583
  • 1
  • 11
  • 36

1 Answers1

0

Your user could just be a pydantic model

Waghabond
  • 1
  • 2
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 18 '23 at 09:56
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33648786) – Daraan Jan 21 '23 at 20:57