Skip to content

Commit f5b454e

Browse files
authored
Update examples.py
1 parent 2915902 commit f5b454e

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

pydantic-for-python-devs/examples.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,51 @@ def validate_password(cls, v):
5959
6060
password="secretpass123"
6161
)
62+
63+
from pydantic import BaseModel
64+
from typing import List, Optional
65+
from datetime import datetime
66+
67+
class Address(BaseModel):
68+
street: str
69+
city: str
70+
state: str
71+
zip_code: str
72+
73+
@field_validator('zip_code')
74+
def validate_zip(cls, v):
75+
if not v.isdigit() or len(v) != 5:
76+
raise ValueError('ZIP code must be 5 digits')
77+
return v
78+
79+
class Contact(BaseModel):
80+
name: str
81+
phone: str
82+
email: Optional[str] = None
83+
84+
class Company(BaseModel):
85+
name: str
86+
founded: datetime
87+
address: Address
88+
contacts: List[Contact]
89+
employee_count: int
90+
is_public: bool = False
91+
92+
# Complex nested data gets fully validated
93+
company_data = {
94+
"name": "Tech Corp",
95+
"founded": "2020-01-15T10:00:00",
96+
"address": {
97+
"street": "123 Main St",
98+
"city": "San Francisco",
99+
"state": "CA",
100+
"zip_code": "94105"
101+
},
102+
"contacts": [
103+
{"name": "John Smith", "phone": "555-0123"},
104+
{"name": "Jane Doe", "phone": "555-0456", "email": "[email protected]"}
105+
],
106+
"employee_count": 150
107+
}
108+
109+
company = Company(**company_data)

0 commit comments

Comments
 (0)