python-attrs / python-attrs/cattrs

structure raises a KeyError when optional attribute is missing

Open
#249 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.1k
Forks
159
Avg merge
12h 21m
Merged PRs (30d)
6

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
    +------------------------------------

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the reported Python example with cattrs 22.1.0 and inspect the structure entry point used by the Dog example. Done means structuring the dictionary without nickname succeeds and produces a Dog instance with the optional attribute unset, while the existing case with nickname continues to work.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.