4

Pydantic copies a model when passing it to the constructor of another model. This fails:

from pydantic import BaseModel

class Child(BaseModel):
    pass
    
class Parent(BaseModel):
    child: Child
        
child = Child()
parent = Parent(child=child)
assert parent.child is child
# Fails

It seems child is copied when passing it to the parent's constructor and therefore the identities of child and parent.child are not the same. I would like to have them to be the same as I need to modify child's attributes later and the changes should be seen in parent.child.

How do I make Pydantic not copy the child?

miksus
  • 2,426
  • 1
  • 18
  • 34

1 Answers1

8

I found the answer myself. Seems this was an issue but it was fixed in a PR by creating a config option copy_on_model_validation. If this option is set to False for the child, then the child is not copied in the construction.

This does not copy the child:

from pydantic import BaseModel

class Child(BaseModel):
    class Config:
        copy_on_model_validation = False

class Parent(BaseModel):
    child: Child

child = Child()
parent = Parent(child=child)
assert parent.child is child
# Passes
miksus
  • 2,426
  • 1
  • 18
  • 34
  • Can anyone explain the choice of (shallow) copy as the default behavior? It seems to go against customary python syntax. – amka66 Sep 06 '22 at 16:30