Skip to content

BaseModel function to initialize a model (when possible) with all default values #2370

Answered by tfwillems
tfwillems asked this question in Question
Discussion options

You must be logged in to vote

Hi @PrettyWood,

Thanks for the very helpful reply! I certainly agree it's far simpler in the case above to simply instantiate with a default as you've done.

But my use case arose more in the context of a GenericModel that contains a submodel. Is there a way to call the cls constructor to instantiate a default in this setting?

from typing import Generic, TypeVar

from pydantic import BaseModel
from pydantic.generics import GenericModel


class SubModelBase(BaseModel):
    y: int = 11


class SubModelExtension(SubModelBase):
    z: int = 12


Input = TypeVar("Input", bound=SubModelBase)


class MyModel(GenericModel, Generic[Input]):
    submodel: Input  # Cannot do = Input()
    x: int = 10


Replies: 3 comments 7 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
7 replies
@PrettyWood
Comment options

@tfwillems
Comment options

@PrettyWood
Comment options

@tfwillems
Comment options

@PrettyWood
Comment options

Answer selected by tfwillems
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants