Skip to content

Commit dac6c33

Browse files
committed
Update docs for deny_unknown_fields
1 parent bff366f commit dac6c33

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

docs/en/class-attributes.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,3 +163,23 @@ class Foo:
163163
See [examples/class_var.py](https://github.com/yukinarit/pyserde/blob/main/examples/class_var.py) for complete example.
164164

165165
[^1]: [dataclasses.fields](https://docs.python.org/3/library/dataclasses.html#dataclasses.fields)
166+
167+
### **`deny_unknown_fields`**
168+
169+
New in v0.22.0, the `deny_unknown_fields` option in the pyserde decorator allows you to enforce strict field validation during deserialization. When this option is enabled, any fields in the input data that are not defined in the target class will cause deserialization to fail with a `SerdeError`.
170+
171+
Consider the following example:
172+
```python
173+
@serde(deny_unknown_fields=True)
174+
class Foo:
175+
a: int
176+
b: str
177+
```
178+
179+
With `deny_unknown_fields=True`, attempting to deserialize data containing fields beyond those defined (a and b in this case) will raise an error. For instance:
180+
```
181+
from_json(Foo, '{"a": 10, "b": "foo", "c": 100.0, "d": true}')
182+
```
183+
This will raise a `SerdeError` since fields c and d are not recognized members of Foo.
184+
185+
See [examples/deny_unknown_fields.py](https://github.com/yukinarit/pyserde/blob/main/examples/deny_unknown_fields.py) for complete example.

docs/ja/class-attributes.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,26 @@ class Foo:
178178
a: ClassVar[int] = 10
179179
```
180180

181-
完全な例については、[examples/class_var.py](https://github.com/yukinarit/pyserde/blob/main/examples/class_var.py) を参照してください。
181+
完全な例については、[examples/class_var.py](https://github.com/yukinarit/pyserde/blob/main/examples/class_var.py)を参照してください。
182182

183183
[^1]: [dataclasses.fields](https://docs.python.org/3/library/dataclasses.html#dataclasses.fields)
184+
185+
### **`deny_unknown_fields`**
186+
187+
バージョン0.22.0で新規追加。 pyserdeデコレータの`deny_unknown_fields`オプションはデシリアライズ時のより厳格なフィールドチェックを制御できます。このオプションをTrueにするとデシリアライズ時に宣言されていないフィールドが見つかると`SerdeError`を投げることができます。
188+
189+
以下の例を考えてください。
190+
```python
191+
@serde(deny_unknown_fields=True)
192+
class Foo:
193+
a: int
194+
b: str
195+
```
196+
197+
`deny_unknown_fields=True`が指定されていると、 宣言されているフィールド(この場合aとb)以外がインプットにあると例外を投げます。例えば、
198+
```
199+
from_json(Foo, '{"a": 10, "b": "foo", "c": 100.0, "d": true}')
200+
```
201+
上記のコードはフィールドcとdという宣言されていないフィールドがあるためエラーとなります。
202+
203+
完全な例については、[examples/deny_unknown_fields.py](https://github.com/yukinarit/pyserde/blob/main/examples/deny_unknown_fields.py)を参照してください。

0 commit comments

Comments
 (0)