1
+ # Import BaseModel from Pydantic for data validation and serialization
2
+ from pydantic import BaseModel
3
+
4
+
5
+ # Define Address model for nested serialization
6
+ class Address (BaseModel ):
7
+ """
8
+ Represents an address with street, city, state, and postal code.
9
+ """
10
+ street : str
11
+ city : str
12
+ state : str
13
+ postal_code : str
14
+
15
+
16
+ # Define Patient model with nested Address
17
+ class Patient (BaseModel ):
18
+ """
19
+ Represents a patient with personal and medical information.
20
+ """
21
+ name : str
22
+ gender : str
23
+ age : int
24
+ address : Address
25
+
26
+
27
+ # Function to print all details of a Patient instance, including nested address
28
+ def print_patient_details (patient : Patient ) -> None :
29
+ """
30
+ Prints the details of a Patient instance, including nested address.
31
+ """
32
+ print (f"Name: { patient .name } " )
33
+ print (f"Gender: { patient .gender } " )
34
+ print (f"Age: { patient .age } " )
35
+ print ("Address:" )
36
+ print (f" Street: { patient .address .street } " )
37
+ print (f" City: { patient .address .city } " )
38
+ print (f" State: { patient .address .state } " )
39
+ print (f" Postal Code: { patient .address .postal_code } " )
40
+
41
+
42
+ # Example usage: Creating Address and Patient instances from dictionaries
43
+ address_data = {
44
+ "street" : "123 Main St" ,
45
+ "city" : "Springfield" ,
46
+ "state" : "IL" ,
47
+ "postal_code" : "62701"
48
+ }
49
+
50
+ patient_data = {
51
+ "name" : "John Doe" ,
52
+ "gender" : "male" ,
53
+ "age" : 30 ,
54
+ "address" : address_data
55
+ }
56
+
57
+ # Create Patient instance from dictionary
58
+ patient1 = Patient (** patient_data )
59
+
60
+ # Demonstrate Pydantic serialization methods
61
+ # model_dump returns a dict representation of the model
62
+ # model_dump_json returns a JSON string, with options to include/exclude fields
63
+ # exclude_unset only includes fields that were set
64
+ temp = patient1 .model_dump # Reference to the model_dump method (not called)
65
+ temp2 = patient1 .model_dump_json (exclude = ["name" , "age" ]) # JSON without name and age
66
+ temp3 = patient1 .model_dump_json (include = ["name" , "age" ]) # JSON with only name and age
67
+ temp4 = patient1 .model_dump_json (exclude_unset = True ) # JSON with only set fields
68
+
69
+ # Print the various serialization outputs
70
+ print (temp2 )
71
+ print (temp3 )
72
+ print (temp4 )
73
+ print (temp ) # This will print the method object, not the data
74
+ print (type (temp ))
75
+ print (type (temp2 ))
0 commit comments