Open
Description
- cattrs version: 22.1.0
- Python version: 3.9.10
- Operating System: macOS Big Sur (11.5.2)
Description
Passing a dictionary to structure
that has missing entries for Optional
values results in an error. Instead I would expect the instance to get built successfully with the optional property unset.
What I Did
Example code:
from cattrs import structure
from attrs import define
from typing import Optional
@define
class Dog:
name: str
nickname: Optional[str]
if __name__ == "__main__":
# This works
spike = structure({"name": "Spike", "nickname": "Carl"}, Dog)
# This raises an error
rex = structure({"name": "Rex"}, Dog)
The result:
+ Exception Group Traceback (most recent call last):
| File "/Users/cmadd/tractable/graphs/cattrs_bug.py", line 13, in <module>
| rex = structure({"name": "Rex"}, Dog)
| File "/Users/cmadd/tractable/graphs/venv/lib/python3.9/site-packages/cattrs/converters.py", line 281, in structure
| return self._structure_func.dispatch(cl)(obj, cl)
| File "<cattrs generated structure __main__.Dog>", line 14, in structure_Dog
| if errors: raise __c_cve('While structuring Dog', errors, __cl)
| cattrs.errors.ClassValidationError: While structuring Dog
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "<cattrs generated structure __main__.Dog>", line 10, in structure_Dog
| res['nickname'] = __c_structure_nickname(o['nickname'], __c_type_nickname)
| KeyError: 'nickname'
| Structuring class Dog @ attribute nickname
+------------------------------------
Metadata
Metadata
Assignees
Labels
No labels