Monday, 20 September 2021

Pydnatic: __fields_set__: Get field names which are set at the time of initialization

__fields_set__ return set of names of fields which were set when the model instance was initialized.

 

Example

emp1.__fields_set__

 

field_set_1.py

from pydantic import BaseModel

class Employee(BaseModel):
    id: int = None
    name: str = None
    age: int = None
    
emp1 = Employee()
emp2 = Employee(id = 1)
emp3 = Employee(id = 1, name = 'Krishna')
emp4 = Employee(id = 1, name = 'Krishna', age = 23)

print(emp1.__fields_set__)
print(emp2.__fields_set__)
print(emp3.__fields_set__)
print(emp4.__fields_set__)

 

Output

set()
{'id'}
{'name', 'id'}
{'age', 'name', 'id'}

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment