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())