Thursday 9 September 2021

Pydantic: copy(): Return a copy of the model

Pydantic model has a copy() method, used to get a copy of the model.

 

Below table summarizes the arguments to be passed to copy() method.

 

Argument

Description

include

fields to include in the returned dictionary

exclude

fields to exclude from the returned dictionary

update

a dictionary of values to change when creating the copied model

deep

whether to make a deep copy of the new model; default False

 

Example

emp1Copy1 = emp1.copy()
emp1Copy2 = emp1.copy(include = {'id', 'name'})
emp1Copy3 = emp1.copy(exclude = {'age'})
emp1Copy4 = emp1.copy(exclude = {'name'}, update = {'age' : 45})

 

copy_method_1.py

 

from pydantic import BaseModel, ValidationError

class Employee(BaseModel):
    id: int
    name: str
    age: int

emp1 = Employee(id = 1, name = 'Krishna', age = 23)

emp1Copy1 = emp1.copy()
emp1Copy2 = emp1.copy(include = {'id', 'name'})
emp1Copy3 = emp1.copy(exclude = {'age'})
emp1Copy4 = emp1.copy(exclude = {'name'}, update = {'age' : 45})

print('emp1Copy1 -> ' + str(emp1Copy1))
print('emp1Copy2 -> ' + str(emp1Copy2))
print('emp1Copy3 -> ' + str(emp1Copy3))
print('emp1Copy4 -> ' + str(emp1Copy4))

 

Output

emp1Copy1 -> id=1 name='Krishna' age=23
emp1Copy2 -> id=1 name='Krishna'
emp1Copy3 -> id=1 name='Krishna'
emp1Copy4 -> id=1 age=45

 

copy() method return a shallow copy of the object by default, set the argument deep to true to get deep copy of the object.

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment