Easily transfer attribute values from one pydantic model instance to another instance.
Let's say that you have a model and one instance:
>>> from pydantic import BaseModel >>> class A(BaseModel): ... field: str ... >>> one = A(field="one") >>> one A(field='one')
The Tedious Copy
When you wanted to create another instance of the model, you could instatiate and then use the setters:
>>> two = A() >>> two.field = one.field >>> two A(field='one')
Or you could set each field in the constructor:
>>> two = A(field=one.field) >>> two A(field='one')
But what if you have a model with twenty fields? This one-by-one copy is too tedious.
The Convenient Splat Copy
The good news is that you can splat all those 20 fields at once into the new instance.
vars() to create a dict of those fields and the
** splat to expand them all into kwargs for the class constructor:
>>> two = A(**vars(one)) >>> two A(field='one')
Any other favorite methods for convenient copying?