Skip to content

Commit 3a77103

Browse files
add pydantic number constraint
1 parent f7e44a3 commit 3a77103

File tree

3 files changed

+202
-49
lines changed

3 files changed

+202
-49
lines changed

Chapter2/dataclasses.ipynb

Lines changed: 0 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -398,55 +398,6 @@
398398
"if not isinstance(dog.age, int):\n",
399399
" raise ValueError(\"Dog's age must be an integer.\")"
400400
]
401-
},
402-
{
403-
"cell_type": "markdown",
404-
"id": "addd6347",
405-
"metadata": {},
406-
"source": [
407-
"### Simplify Data Validation with Pydantic"
408-
]
409-
},
410-
{
411-
"cell_type": "markdown",
412-
"id": "e4bb3a40",
413-
"metadata": {},
414-
"source": [
415-
"Dataclasses require manual implementation of validation.\n",
416-
"\n",
417-
"On the other hand, Pydantic offers built-in validation that automatically validates data and provides informative error messages. This makes Pydantic particularly useful when working with data from external sources.\n"
418-
]
419-
},
420-
{
421-
"cell_type": "code",
422-
"execution_count": 3,
423-
"id": "3aaa4b09",
424-
"metadata": {},
425-
"outputs": [
426-
{
427-
"ename": "ValidationError",
428-
"evalue": "1 validation error for Dog\nage\n Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='ten', input_type=str]\n For further information visit https://errors.pydantic.dev/2.5/v/int_parsing",
429-
"output_type": "error",
430-
"traceback": [
431-
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
432-
"\u001b[0;31mValidationError\u001b[0m Traceback (most recent call last)",
433-
"Cell \u001b[0;32mIn[3], line 9\u001b[0m\n\u001b[1;32m 5\u001b[0m names: \u001b[38;5;28mstr\u001b[39m\n\u001b[1;32m 6\u001b[0m age: \u001b[38;5;28mint\u001b[39m\n\u001b[0;32m----> 9\u001b[0m dog \u001b[38;5;241m=\u001b[39m \u001b[43mDog\u001b[49m\u001b[43m(\u001b[49m\u001b[43mnames\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mBim\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mage\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mten\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n",
434-
"File \u001b[0;32m~/book/venv/lib/python3.11/site-packages/pydantic/main.py:164\u001b[0m, in \u001b[0;36mBaseModel.__init__\u001b[0;34m(__pydantic_self__, **data)\u001b[0m\n\u001b[1;32m 162\u001b[0m \u001b[38;5;66;03m# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks\u001b[39;00m\n\u001b[1;32m 163\u001b[0m __tracebackhide__ \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[0;32m--> 164\u001b[0m \u001b[43m__pydantic_self__\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m__pydantic_validator__\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mvalidate_python\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdata\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mself_instance\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m__pydantic_self__\u001b[49m\u001b[43m)\u001b[49m\n",
435-
"\u001b[0;31mValidationError\u001b[0m: 1 validation error for Dog\nage\n Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='ten', input_type=str]\n For further information visit https://errors.pydantic.dev/2.5/v/int_parsing"
436-
]
437-
}
438-
],
439-
"source": [
440-
"from pydantic import BaseModel\n",
441-
"\n",
442-
"\n",
443-
"class Dog(BaseModel):\n",
444-
" names: str\n",
445-
" age: int\n",
446-
"\n",
447-
"\n",
448-
"dog = Dog(names=\"Bim\", age=\"ten\")"
449-
]
450401
}
451402
],
452403
"metadata": {

Chapter2/pydantic.ipynb

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"id": "3569bdc8",
6+
"metadata": {},
7+
"source": [
8+
"## Pydantic"
9+
]
10+
},
11+
{
12+
"cell_type": "markdown",
13+
"id": "ada65a73",
14+
"metadata": {},
15+
"source": [
16+
"### Simplify Data Validation with Pydantic"
17+
]
18+
},
19+
{
20+
"cell_type": "markdown",
21+
"id": "0f82baff",
22+
"metadata": {},
23+
"source": [
24+
"Dataclasses require manual implementation of validation.\n",
25+
"\n",
26+
"On the other hand, Pydantic offers built-in validation that automatically validates data and provides informative error messages. This makes Pydantic particularly useful when working with data from external sources.\n"
27+
]
28+
},
29+
{
30+
"cell_type": "code",
31+
"execution_count": null,
32+
"id": "9bc629b5",
33+
"metadata": {},
34+
"outputs": [
35+
{
36+
"ename": "ValidationError",
37+
"evalue": "1 validation error for Dog\nage\n Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='ten', input_type=str]\n For further information visit https://errors.pydantic.dev/2.5/v/int_parsing",
38+
"output_type": "error",
39+
"traceback": [
40+
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n",
41+
"\u001b[0;31mValidationError\u001b[0m Traceback (most recent call last)\n",
42+
"Cell \u001b[0;32mIn[3], line 9\u001b[0m\n",
43+
"\u001b[1;32m 5\u001b[0m names: \u001b[38;5;28mstr\u001b[39m\n",
44+
"\u001b[1;32m 6\u001b[0m age: \u001b[38;5;28mint\u001b[39m\n",
45+
"\u001b[0;32m----> 9\u001b[0m dog \u001b[38;5;241m=\u001b[39m \u001b[43mDog\u001b[49m\u001b[43m(\u001b[49m\u001b[43mnames\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mBim\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mage\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mten\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n",
46+
"\n",
47+
"File \u001b[0;32m~/book/venv/lib/python3.11/site-packages/pydantic/main.py:164\u001b[0m, in \u001b[0;36mBaseModel.__init__\u001b[0;34m(__pydantic_self__, **data)\u001b[0m\n",
48+
"\u001b[1;32m 162\u001b[0m \u001b[38;5;66;03m# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks\u001b[39;00m\n",
49+
"\u001b[1;32m 163\u001b[0m __tracebackhide__ \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mTrue\u001b[39;00m\n",
50+
"\u001b[0;32m--> 164\u001b[0m \u001b[43m__pydantic_self__\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m__pydantic_validator__\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mvalidate_python\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdata\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mself_instance\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m__pydantic_self__\u001b[49m\u001b[43m)\u001b[49m\n",
51+
"\n",
52+
"\u001b[0;31mValidationError\u001b[0m: 1 validation error for Dog\n",
53+
"age\n",
54+
" Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='ten', input_type=str]\n",
55+
" For further information visit https://errors.pydantic.dev/2.5/v/int_parsing"
56+
]
57+
}
58+
],
59+
"source": [
60+
"from pydantic import BaseModel\n",
61+
"\n",
62+
"\n",
63+
"class Dog(BaseModel):\n",
64+
" names: str\n",
65+
" age: int\n",
66+
"\n",
67+
"\n",
68+
"dog = Dog(names=\"Bim\", age=\"ten\")"
69+
]
70+
},
71+
{
72+
"cell_type": "markdown",
73+
"id": "15dd5037",
74+
"metadata": {},
75+
"source": [
76+
"### Use Pydantic's Field Class to Validate Numbers and Dates"
77+
]
78+
},
79+
{
80+
"cell_type": "code",
81+
"execution_count": null,
82+
"id": "eb27ed75",
83+
"metadata": {
84+
"tags": [
85+
"hide-cell"
86+
]
87+
},
88+
"outputs": [],
89+
"source": [
90+
"!pip install pydantic"
91+
]
92+
},
93+
{
94+
"cell_type": "markdown",
95+
"id": "082a6675",
96+
"metadata": {},
97+
"source": [
98+
"In addition to checking the type, you may also want to check if numbers and dates match specific constraints. Pydantic's Field class provides keyword arguments that make this easy."
99+
]
100+
},
101+
{
102+
"cell_type": "code",
103+
"execution_count": 1,
104+
"id": "49c502e7",
105+
"metadata": {},
106+
"outputs": [
107+
{
108+
"ename": "ValidationError",
109+
"evalue": "2 validation errors for Song\nrelease_date\n Input should be less than 2024-05-10 [type=less_than, input_value=datetime.date(2024, 6, 1), input_type=date]\n For further information visit https://errors.pydantic.dev/2.5/v/less_than\nbeats_per_minute\n Field required [type=missing, input_value={'title': 'Believer', 'ar...2024, 6, 1), 'bpm': 125}, input_type=dict]\n For further information visit https://errors.pydantic.dev/2.5/v/missing",
110+
"output_type": "error",
111+
"traceback": [
112+
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
113+
"\u001b[0;31mValidationError\u001b[0m Traceback (most recent call last)",
114+
"Cell \u001b[0;32mIn[1], line 14\u001b[0m\n\u001b[1;32m 10\u001b[0m beats_per_minute: \u001b[38;5;28mint\u001b[39m \u001b[38;5;241m=\u001b[39m Field(multiple_of\u001b[38;5;241m=\u001b[39m\u001b[38;5;241m5\u001b[39m)\n\u001b[1;32m 13\u001b[0m \u001b[38;5;66;03m# Example usage\u001b[39;00m\n\u001b[0;32m---> 14\u001b[0m song1 \u001b[38;5;241m=\u001b[39m \u001b[43mSong\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 15\u001b[0m \u001b[43m \u001b[49m\u001b[43mtitle\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mBeliever\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 16\u001b[0m \u001b[43m \u001b[49m\u001b[43martist\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mImagine Dragons\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 17\u001b[0m \u001b[43m \u001b[49m\u001b[43mduration\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m3.67\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 18\u001b[0m \u001b[43m \u001b[49m\u001b[43mrelease_date\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdate\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m2024\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m6\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 19\u001b[0m \u001b[43m \u001b[49m\u001b[43mbpm\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m125\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 20\u001b[0m \u001b[43m)\u001b[49m\n",
115+
"File \u001b[0;32m~/book/venv/lib/python3.11/site-packages/pydantic/main.py:164\u001b[0m, in \u001b[0;36mBaseModel.__init__\u001b[0;34m(__pydantic_self__, **data)\u001b[0m\n\u001b[1;32m 162\u001b[0m \u001b[38;5;66;03m# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks\u001b[39;00m\n\u001b[1;32m 163\u001b[0m __tracebackhide__ \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[0;32m--> 164\u001b[0m \u001b[43m__pydantic_self__\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m__pydantic_validator__\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mvalidate_python\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdata\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mself_instance\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m__pydantic_self__\u001b[49m\u001b[43m)\u001b[49m\n",
116+
"\u001b[0;31mValidationError\u001b[0m: 2 validation errors for Song\nrelease_date\n Input should be less than 2024-05-10 [type=less_than, input_value=datetime.date(2024, 6, 1), input_type=date]\n For further information visit https://errors.pydantic.dev/2.5/v/less_than\nbeats_per_minute\n Field required [type=missing, input_value={'title': 'Believer', 'ar...2024, 6, 1), 'bpm': 125}, input_type=dict]\n For further information visit https://errors.pydantic.dev/2.5/v/missing"
117+
]
118+
}
119+
],
120+
"source": [
121+
"from pydantic import BaseModel, Field\n",
122+
"from datetime import date\n",
123+
"\n",
124+
"\n",
125+
"class Song(BaseModel):\n",
126+
" title: str\n",
127+
" artist: str\n",
128+
" duration: float = Field(gt=0.0)\n",
129+
" release_date: date = Field(lt=date.today())\n",
130+
" beats_per_minute: int = Field(multiple_of=5)\n",
131+
"\n",
132+
"\n",
133+
"song1 = Song(\n",
134+
" title=\"Believer\",\n",
135+
" artist=\"Imagine Dragons\",\n",
136+
" duration=3.67,\n",
137+
" release_date=date(2024, 6, 1), \n",
138+
" bpm=125,\n",
139+
")"
140+
]
141+
},
142+
{
143+
"cell_type": "code",
144+
"execution_count": 2,
145+
"id": "d05c1ff0",
146+
"metadata": {},
147+
"outputs": [
148+
{
149+
"ename": "ValidationError",
150+
"evalue": "2 validation errors for Song\nduration\n Input should be greater than 0 [type=greater_than, input_value=0, input_type=int]\n For further information visit https://errors.pydantic.dev/2.5/v/greater_than\nbeats_per_minute\n Field required [type=missing, input_value={'title': 'Thunder', 'art...017, 4, 27), 'bpm': 165}, input_type=dict]\n For further information visit https://errors.pydantic.dev/2.5/v/missing",
151+
"output_type": "error",
152+
"traceback": [
153+
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
154+
"\u001b[0;31mValidationError\u001b[0m Traceback (most recent call last)",
155+
"Cell \u001b[0;32mIn[2], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m song2 \u001b[38;5;241m=\u001b[39m \u001b[43mSong\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 2\u001b[0m \u001b[43m \u001b[49m\u001b[43mtitle\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mThunder\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3\u001b[0m \u001b[43m \u001b[49m\u001b[43martist\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mImagine Dragons\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 4\u001b[0m \u001b[43m \u001b[49m\u001b[43mduration\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 5\u001b[0m \u001b[43m \u001b[49m\u001b[43mrelease_date\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mdate\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m2017\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m4\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m27\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 6\u001b[0m \u001b[43m \u001b[49m\u001b[43mbpm\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m165\u001b[39;49m\n\u001b[1;32m 7\u001b[0m \u001b[43m)\u001b[49m\n",
156+
"File \u001b[0;32m~/book/venv/lib/python3.11/site-packages/pydantic/main.py:164\u001b[0m, in \u001b[0;36mBaseModel.__init__\u001b[0;34m(__pydantic_self__, **data)\u001b[0m\n\u001b[1;32m 162\u001b[0m \u001b[38;5;66;03m# `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks\u001b[39;00m\n\u001b[1;32m 163\u001b[0m __tracebackhide__ \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mTrue\u001b[39;00m\n\u001b[0;32m--> 164\u001b[0m \u001b[43m__pydantic_self__\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m__pydantic_validator__\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mvalidate_python\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdata\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mself_instance\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m__pydantic_self__\u001b[49m\u001b[43m)\u001b[49m\n",
157+
"\u001b[0;31mValidationError\u001b[0m: 2 validation errors for Song\nduration\n Input should be greater than 0 [type=greater_than, input_value=0, input_type=int]\n For further information visit https://errors.pydantic.dev/2.5/v/greater_than\nbeats_per_minute\n Field required [type=missing, input_value={'title': 'Thunder', 'art...017, 4, 27), 'bpm': 165}, input_type=dict]\n For further information visit https://errors.pydantic.dev/2.5/v/missing"
158+
]
159+
}
160+
],
161+
"source": [
162+
"song2 = Song(\n",
163+
" title=\"Thunder\",\n",
164+
" artist=\"Imagine Dragons\",\n",
165+
" duration=0,\n",
166+
" release_date=date(2017, 4, 27),\n",
167+
" bpm=165\n",
168+
")"
169+
]
170+
},
171+
{
172+
"cell_type": "markdown",
173+
"id": "60b73d45",
174+
"metadata": {},
175+
"source": [
176+
"[Learn more about Pydantic's numeric constraints](https://bit.ly/4bbhthb)."
177+
]
178+
}
179+
],
180+
"metadata": {
181+
"kernelspec": {
182+
"display_name": "venv",
183+
"language": "python",
184+
"name": "python3"
185+
},
186+
"language_info": {
187+
"codemirror_mode": {
188+
"name": "ipython",
189+
"version": 3
190+
},
191+
"file_extension": ".py",
192+
"mimetype": "text/x-python",
193+
"name": "python",
194+
"nbconvert_exporter": "python",
195+
"pygments_lexer": "ipython3",
196+
"version": "3.11.6"
197+
}
198+
},
199+
"nbformat": 4,
200+
"nbformat_minor": 5
201+
}

_toc.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ chapters:
3636
- file: Chapter2/dataclasses.ipynb
3737
- file: Chapter2/typing.ipynb
3838
- file: Chapter2/pathlib.ipynb
39+
- file: Chapter2/pydantic.ipynb
3940
- file: Chapter3/Chapter3.md
4041
sections:
4142
- file: Chapter3/change_values.ipynb

0 commit comments

Comments
 (0)