Skip to content

Commit 70587e2

Browse files
feature: Add DeserializeAs setting
1 parent b0549d9 commit 70587e2

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
[[entries]]
2+
id = "34f4cbf8-4bd4-4b6d-837f-6bf4b2006803"
3+
type = "feature"
4+
description = "Add `DeserializeAs` setting"
5+
author = "@NiklasRosenstein"

databind.core/src/databind/core/settings.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,38 @@ class SerializeDefaults(BooleanSetting):
326326
to how the name of the setting appears assertive of the fact that the instance indicates the setting is enabled."""
327327

328328

329-
# NOTE(NiklasRosenstein): For Python 3.6, metadata passed into Annotated[...] must be hashable.
329+
@dataclasses.dataclass
330+
class DeserializeAs(Setting):
331+
"""Indicates that a field should be deserialized as the given type instead of the type of the field. This is
332+
typically used when a field should be typed as an abstract class or interface, but during deserialization of the
333+
field, a concrete type should be used instead.
334+
335+
Example:
336+
337+
```py
338+
import typing
339+
from dataclasses import dataclass
340+
from databind.core.settings import DeserializeAs
341+
342+
@dataclass
343+
class A:
344+
pass
345+
346+
@dataclass
347+
class B(A):
348+
pass
349+
350+
@dataclass
351+
class MyClass:
352+
my_field: typing.Annotated[A, DeserializeAs(B)]
353+
```
354+
355+
Here, although `MyClass.my_field` is annotated as `A`, when a payload is deserialized into an instance of
356+
`MyClass`, the value for `my_field` will be deserialized as an instance of `B` instead of `A`.
357+
"""
358+
359+
type: t.Type[t.Any]
360+
priority: Priority = Priority.NORMAL
330361

331362

332363
@dataclasses.dataclass

0 commit comments

Comments
 (0)