-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathpydantic-wrong.html
More file actions
250 lines (219 loc) · 18.5 KB
/
pydantic-wrong.html
File metadata and controls
250 lines (219 loc) · 18.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
<html>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<head>
<title>
leontrolski - I've been holding Pydantic wrong
</title>
<style>
body {margin: 5% auto; background: #fff7f7; color: #444444; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.8; max-width: 63%;}
@media screen and (max-width: 800px) {body {font-size: 14px; line-height: 1.4; max-width: 90%;}}
pre {width: 100%; border-top: 3px solid gray; border-bottom: 3px solid gray;}
a {border-bottom: 1px solid #444444; color: #444444; text-decoration: none; text-shadow: 0 1px 0 #ffffff; }
a:hover {border-bottom: 0;}
.inline {background: #b3b2b226; padding-left: 0.3em; padding-right: 0.3em; white-space: nowrap;}
blockquote {font-style: italic;color:black;background-color:#f2f2f2;padding:2em;}
details {border-bottom:solid 5px gray;}
</style>
<link href="https://unpkg.com/prism-themes@1.9.0/themes/prism-darcula.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.20.0/components/prism-core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.20.0/plugins/autoloader/prism-autoloader.min.js"></script>
</head>
<body>
<a href="index.html">
<img src="pic.png" style="height:2em">
⇦
</a>
<p><i>2026-01-26</i></p>
<h1 id="i-ve-been-holding-pydantic-wrong">I've been holding Pydantic wrong</h1>
<p>I'm a long time Pydantic user - it's the idiomatic approach to <a href="https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/">parse don't validate</a> for Python - I advocate running it over <em>all</em> data that doesn't come from your codebase (<form> input, JSON from the db, queue data, CSV data, etc).</p>
<p>Pydantic has been around for a while and there's a many ways of using it, following are my recommendations as of now. <em>Jump straight to <a href="#example">definitive example</a>.</em></p>
<hr>
<p>The first one is the biggest and most contentious:</p>
<h2 id="stop-using-pydantic-basemodel-">Stop using <code>pydantic.BaseModel</code></h2>
<p>Instead, <a href="https://docs.pydantic.dev/latest/concepts/dataclasses/">use stdlib <code>dataclass</code>s</a> in conjunction with <a href="https://docs.pydantic.dev/latest/concepts/type_adapter/"><code>pydantic.TypeAdapter</code></a>.</p>
<p>There are a number of reasons why you should do this:</p>
<h3 id="internally-you-don-t-want-validation">Internally, you don't want validation</h3>
<p>Validation should be an explicit step at the boundaries of your application, eg:</p>
<pre><code class="lang-python"><span class="hljs-attr">x</span> = pydantic.TypeAdapter(MyDataclass).validate_python(request.post_data)
</code></pre>
<p>The conventional approach is also fine at the system boundaries:</p>
<pre><code class="lang-python"><span class="hljs-attr">x</span> = MyBaseModel(**request.post_data)
</code></pre>
<p><em>But</em> you end up performing validation where you don't need to, eg. when calling <code>MyBaseModel(a=a, b=b)</code> deep within your application.</p>
<p>Validation incurs some runtime cost (admittedly fairly small as of Pydantic v2) - the bigger issue is the increased API surface area of the data being passed round your application. As a developer, I'd like to look at <code>MyBaseModel(a=a, b=b)</code> and think "an object is being initialized", not "an object is being initialized, it calls any number of validators, it may raise a <code>pydantic.ValidationError</code>, it may trigger a costly model rebuild". This is a similar problem to pervasive use of ORM instances.</p>
<p>Once you've validated data that enters the application, lean on <code>mypy</code> to make sure everything lines up, not runtime validation.</p>
<h3 id="consistency-of-pydantic-api-usage">Consistency of Pydantic API usage</h3>
<p>Say you're parsing configuration from a csv, you should use Pydantic to gracefully handle date parsing etc:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> csv:
typed_row = pydantic.TypeAdapter(tuple[<span class="hljs-selector-tag">dt</span><span class="hljs-selector-class">.date</span>, int]).validate_python(row)
</code></pre>
<p>Using <code>TypeAdapter</code>, validation is explicit and it looks the same everywhere.</p>
<h3 id="consistency-of-your-types">Consistency of your types</h3>
<p>In a modern typed Python codebase, <code>dataclass</code>s should be your bread-and-butter struct type <em>(the value-added of <code>attrs</code> aren't worth deviating from the stdlib for)</em>. Having your datatypes be <em>only</em> composed of <code>dataclass</code>s, <code>list</code>s, <code>dict</code>s etc. and no other custom types makes it far easier to write generic code in the form:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">transform</span><span class="hljs-params">(v: T)</span> -> T:</span>
<span class="hljs-keyword">if</span> isinstance(v, list):
<span class="hljs-keyword">return</span> [transform(x) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> v]
<span class="hljs-keyword">if</span> isinstance(v, dict):
...
<span class="hljs-keyword">if</span> is_dataclass(v):
<span class="hljs-keyword">return</span> v.__class__(**{field.name: transform(getattr(v, field.name) <span class="hljs-keyword">for</span> field <span class="hljs-keyword">in</span> fields(v)})
<span class="hljs-keyword">raise</span> TypeError(f<span class="hljs-string">"Unknown type {v.__class__}"</span>)
</code></pre>
<p>Using <code>BaseModel</code> means another type of object that you (and other library maintainers) have to consider when writing generic functions.</p>
<h3 id="model-rebuilding">Model rebuilding</h3>
<p>When you have loads of nested models, it can be costly to initialize the classes themselves and you can end up with strange import-order problems. This can be somewhat surmounted on a <code>BaseModel</code> with <a href="https://docs.pydantic.dev/latest/api/config/#pydantic.config.ConfigDict.defer_build"><code>defer_build=True</code></a> - then the build is triggered at the first call to <code>MyBaseModel(a=a, b=b)</code>.</p>
<p>By explicity using <code>pydantic.TypeAdapter</code>, you <em>know</em> where the costly initialization is going to take place - it's not going to happen in some random test where you didn't even require validation.</p>
<h3 id="deep-error-handling">Deep error handling</h3>
<p>Consider this bug:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_route_handler</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-keyword">try</span>:
_process_data(request)
<span class="hljs-keyword">except</span> pydantic.ValidationError <span class="hljs-keyword">as</span> e:
<span class="hljs-keyword">return</span> Response422(e)
...
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_process_data</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-comment"># This might raise a `ValidationError`, but we didn't want to catch it</span>
x = MyOtherBaseModel(a=a, b=b)
<span class="hljs-comment"># We do want to catch `ValidationError`s raised here</span>
y = MyBaseModel(**request.post_data)
...
</code></pre>
<p>By making validation explicit, you massively reduce the chance of these kind of bugs.</p>
<h3 id="type-checking">Type checking</h3>
<p>Without any configuration, mypy understands <code>my_tuple = pydantic.TypeAdapter(tuple[int, str]).validate_python(v)</code></p>
<p>For <code>pydantic.BaseModel</code>s to typecheck correctly on <code>__init__</code>, we need to add the following to our <code>pyproject.toml</code>:</p>
<pre><code class="lang-toml"><span class="hljs-section">[tool.mypy]</span>
<span class="hljs-attr">plugins</span> = [<span class="hljs-string">"pydantic.mypy"</span>]
<span class="hljs-section">
[tool.pydantic-mypy]</span>
<span class="hljs-attr">init_forbid_extra</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">init_typed</span> = <span class="hljs-literal">true</span>
<span class="hljs-attr">warn_required_dynamic_aliases</span> = <span class="hljs-literal">true</span>
</code></pre><p>There are two problems here:</p>
<ul>
<li>As a library writer, you can't guarantee your consumers will even be able to add that configuration.</li>
<li>It's not possible to use other typecheckers.</li>
</ul>
<h3 id="compatability-with-fastapi">Compatability with FastAPI</h3>
<p>FastAPI <a href="https://fastapi.tiangolo.com/advanced/dataclasses/">is compatible with <code>dataclass</code>s</a>.</p>
<hr>
<h2 id="use-annotated-">Use <code>Annotated</code></h2>
<p>Use the <a href="https://docs.pydantic.dev/latest/concepts/fields/#the-annotated-pattern">Annotated pattern</a> for the reasons outlined in the docs.</p>
<h2 id="validation">Validation</h2>
<p>I've had various issues when composing <code>BeforeValidator|AfterValidator|PlainSerializer</code> with deeply nested <code>Annotated</code> types. Always use <code>WrapValidator|WrapSerializer</code>:</p>
<pre><code class="lang-python">def _date_short_validator(v: Any, <span class="hljs-keyword">handler</span>: Callable[[<span class="hljs-keyword">Any</span>], <span class="hljs-keyword">Any</span>]) -> <span class="hljs-keyword">Any</span>:
<span class="hljs-keyword">if</span> isinstance(v, <span class="hljs-keyword">str</span>):
v = dt.datetime.strptime(v, <span class="hljs-string">"%y%m%d"</span>)
<span class="hljs-keyword">return</span> <span class="hljs-keyword">handler</span>(v)
<span class="hljs-keyword">def</span> _date_short_serializer(v: <span class="hljs-keyword">Any</span>, <span class="hljs-keyword">handler</span>: <span class="hljs-keyword">Any</span>, info: <span class="hljs-keyword">Any</span>) -> <span class="hljs-keyword">Any</span>:
<span class="hljs-keyword">if</span> isinstance(v, dt.date):
<span class="hljs-keyword">return</span> v.strftime(<span class="hljs-string">"%y%m%d"</span>)
<span class="hljs-keyword">return</span> <span class="hljs-keyword">handler</span>(v)
DateShort = Annotated[
dt.date,
pydantic.WrapValidator(_date_short_validator),
pydantic.WrapSerializer(_date_short_serializer),
]
@dataclass(kw_only=<span class="hljs-literal">True</span>)
<span class="hljs-keyword">class</span> Foo:
<span class="hljs-built_in">date</span>: DateShort
</code></pre>
<p>As of 3.14, rather than use Pydantic's own <code>context</code> gubbins, use the <a href="https://docs.python.org/3/library/contextvars.html">stdlib</a>:</p>
<pre><code class="lang-python">date_format: contextvars.ContextVar[str] = contextvars.ContextVar(
<span class="hljs-string">"date_format"</span>, <span class="hljs-keyword">default</span>=<span class="hljs-string">"%y%m%d"</span>
)
<span class="hljs-keyword">def</span> _date_short_validator(v: <span class="hljs-keyword">Any</span>, handler: Callable[[<span class="hljs-keyword">Any</span>], <span class="hljs-keyword">Any</span>]) -> <span class="hljs-keyword">Any</span>:
<span class="hljs-keyword">if</span> isinstance(v, str):
v = dt.datetime.strptime(v, date_format.get())
<span class="hljs-keyword">return</span> handler(v)
with date_format.set(<span class="hljs-string">"%Y-%m-%d"</span>):
pydantic.TypeAdapter(Foo).validate_python({<span class="hljs-string">"date"</span>: <span class="hljs-string">"2025-12-31"</span>})
</code></pre>
<p>When doing class-level validation or setting derived default values, do:</p>
<pre><code class="lang-python"><span class="hljs-meta">@dataclass(kw_only=True)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span>:</span>
a: int | <span class="hljs-keyword">None</span> = <span class="hljs-keyword">None</span>
b: int | <span class="hljs-keyword">None</span> = <span class="hljs-keyword">None</span>
<span class="hljs-meta"> @pydantic.model_validator(mode="after")</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_for_a_or_b</span><span class="hljs-params">(self)</span> -> Self:</span>
<span class="hljs-keyword">if</span> self.a <span class="hljs-keyword">is</span> <span class="hljs-keyword">None</span> <span class="hljs-keyword">and</span> self.b <span class="hljs-keyword">is</span> <span class="hljs-keyword">None</span>:
<span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Expected a or b"</span>)
<span class="hljs-keyword">return</span> self
</code></pre>
<h2 id="discriminated-unions">Discriminated unions</h2>
<p>Where possible, bother to <a href="https://docs.pydantic.dev/latest/concepts/unions/#discriminated-unions-with-callable-discriminator">explicitly discriminate unions</a>, it makes for far nicer error messages.</p>
<h1 id="example">The definitive way to use Pydantic right now - example</h1>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> functools
<span class="hljs-keyword">import</span> pydantic
<span class="hljs-keyword">import</span> datetime <span class="hljs-keyword">as</span> dt
<span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> dataclass, field
<span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> Any, Annotated, Callable, Self, TypeVar
<span class="hljs-keyword">import</span> pydantic
<span class="hljs-keyword">import</span> contextvars
<span class="hljs-comment"># mypy often struggles with `functools.cache`</span>
cache: Callable[[T], T] = functools.cache <span class="hljs-comment"># type: ignore</span>
T = TypeVar(<span class="hljs-string">"T"</span>)
<span class="hljs-comment"># Do different validations in different contexts</span>
date_format: contextvars.ContextVar[str] = contextvars.ContextVar(
<span class="hljs-string">"date_format"</span>, default=<span class="hljs-string">"%y%m%d"</span>
)
<span class="hljs-comment"># Always use WrapValidator|WrapSerializer</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_date_short_validator</span><span class="hljs-params">(v: Any, handler: Callable[[Any], Any])</span> -> Any:</span>
<span class="hljs-keyword">if</span> isinstance(v, str):
v = dt.datetime.strptime(v, date_format.get())
<span class="hljs-keyword">return</span> handler(v)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_date_short_serializer</span><span class="hljs-params">(v: Any, handler: Any, info: Any)</span> -> Any:</span>
<span class="hljs-keyword">if</span> isinstance(v, dt.date):
<span class="hljs-keyword">return</span> v.strftime(date_format.get())
<span class="hljs-keyword">return</span> handler(v)
DateShort = Annotated[
dt.date,
pydantic.WrapValidator(_date_short_validator),
pydantic.WrapSerializer(_date_short_serializer),
]
<span class="hljs-comment"># Don't use `BaseModel`</span>
<span class="hljs-meta">@dataclass(kw_only=True)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyDataclass</span>:</span>
date: DateShort
a: int | <span class="hljs-keyword">None</span> = <span class="hljs-keyword">None</span>
b: int | <span class="hljs-keyword">None</span> = <span class="hljs-keyword">None</span>
<span class="hljs-comment"># Always use `Annotated`</span>
x: Annotated[
list[str],
<span class="hljs-comment"># Adding to the JSONSchema</span>
pydantic.Field(json_schema_extra={<span class="hljs-string">"x-foo"</span>: <span class="hljs-number">1</span>}),
] = field(default_factory=list)
<span class="hljs-comment"># Model level checks</span>
<span class="hljs-meta"> @pydantic.model_validator(mode="after")</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">check_for_a_or_b</span><span class="hljs-params">(self)</span> -> Self:</span>
<span class="hljs-keyword">if</span> self.a <span class="hljs-keyword">is</span> <span class="hljs-keyword">None</span> <span class="hljs-keyword">and</span> self.b <span class="hljs-keyword">is</span> <span class="hljs-keyword">None</span>:
<span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"Expected a or b"</span>)
<span class="hljs-keyword">return</span> self
<span class="hljs-comment"># Add configuration</span>
__pydantic_config__ = pydantic.ConfigDict(
str_to_upper=<span class="hljs-keyword">True</span>,
)
<span class="hljs-meta">@cache # constructing `TypeAdapter`s is slow</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">type_adapter</span><span class="hljs-params">(cls: type[T])</span> -> pydantic.TypeAdapter[T]:</span>
<span class="hljs-keyword">return</span> pydantic.TypeAdapter(cls)
<span class="hljs-comment"># Validate any type</span>
my_tuple = type_adapter(tuple[int, str]).validate_python([<span class="hljs-number">1</span>, <span class="hljs-string">"two"</span>])
my_dataclass = type_adapter(MyDataclass).validate_python(
{
<span class="hljs-string">"x"</span>: [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>],
<span class="hljs-string">"date"</span>: <span class="hljs-string">"251231"</span>,
<span class="hljs-string">"a"</span>: <span class="hljs-number">1</span>,
<span class="hljs-comment"># We ignore extra fields on `.validate_python()` but not on `__init__`</span>
<span class="hljs-string">"extra"</span>: <span class="hljs-number">0</span>,
},
)
<span class="hljs-comment"># Serialize data</span>
jsonable = type_adapter(MyDataclass).dump_python(my_dataclass, mode=<span class="hljs-string">"json"</span>)
<span class="hljs-comment"># Construct JSONSchema</span>
json_schema = type_adapter(MyDataclass).json_schema()
<span class="hljs-comment"># Use the context</span>
<span class="hljs-keyword">with</span> date_format.set(<span class="hljs-string">"%Y-%m-%d"</span>):
my_dataclass = type_adapter(MyDataclass).validate_python(...)
</code></pre>
</body>
</html>