Skip to content

Commit

Permalink
Add Type Adapter Docs example codes & information about dump_json() (p…
Browse files Browse the repository at this point in the history
…ydantic#9477)

Co-authored-by: Sydney Runkle <54324534+sydney-runkle@users.noreply.github.com>
  • Loading branch information
WinterBlue16 and sydney-runkle authored May 22, 2024
1 parent bcac9a2 commit 87adc65
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion docs/concepts/type_adapter.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ class User(TypedDict):


user_list_adapter = TypeAdapter(List[User])
print(repr(user_list_adapter.validate_python([{'name': 'Fred', 'id': '3'}])))
user_list = user_list_adapter.validate_python([{'name': 'Fred', 'id': '3'}])
print(repr(user_list))
#> [{'name': 'Fred', 'id': 3}]

try:
Expand All @@ -40,8 +41,17 @@ except ValidationError as e:
0.id
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='wrong', input_type=str]
"""

print(repr(user_list_adapter.dump_json(user_list)))
#> b'[{"name":"Fred","id":3}]'
```

!!! info "`dump_json` returns `bytes`"
`TypeAdapter`'s `dump_json` methods returns a `bytes` object, unlike the corresponding method for `BaseModel`, `model_dump_json`, which returns a `str`.
The reason for this discrepancy is that in V1, model dumping returned a str type, so this behavior is retained in V2 for backwards compatibility.
For the `BaseModel` case, `bytes` are coerced to `str` types, but `bytes` are often the desired end type.
Hence, for the new `TypeAdapter` class in V2, the return type is simply `bytes`, which can easily be coerced to a `str` type if desired.

!!! note
Despite some overlap in use cases with [`RootModel`][pydantic.root_model.RootModel],
[`TypeAdapter`][pydantic.type_adapter.TypeAdapter] should not be used as a type annotation for
Expand Down

0 comments on commit 87adc65

Please sign in to comment.