Skip to content

GenConverter fails to structure when init=False attributes are present #166

@bushkov

Description

@bushkov
  • cattrs version: 1.8.0
  • Python version: 3.8.11
  • Operating System: macOS 11.5.2

Description

I am trying to structure an attrs class that contains an attribute which shouldn't be initialized on instance creation. When I use Converter, the structuring works fine, but when I use GenConverter it fails.

What I Did

Here is a simple example that fails:

import attr
import cattr


c = cattr.GenConverter()

@attr.s
class A:
    x: int = attr.ib()
    y: int = attr.ib(init=False)


d = {"x": 0}

c.structure(d, A)

It fails with:

Traceback (most recent call last):
  File "example.py", line 15, in <module>
    c.structure(d, A)
  File "cattr/converters.py", line 294, in structure
    return self._structure_func.dispatch(cl)(obj, cl)
  File "<cattrs generated structure __main__.A>", line 4, in structure_A
KeyError: 'y'

On a related note it's not clear to me from the documentation in which situation one should prefer to use Converter and in which situation one should prefer GenConverter. In particular the following points are unclear:

GenConverter differs from the old cattr.Converter in the following ways:

  • structuring and unstructuring of attrs classes is slower the first time, but faster every subsequent time
  • structuring and unstructuring can be customized
  • support for easy overriding collection unstructuring

By 'faster every subsequent time' does it mean that GenConverter is faster than Converter or does it mean that it's getting faster with every structure/unstructure, but not faster than Converter?

About 'structuring and unstructuring can be customized' and support for easy overriding collection unstructuring, it would be helpful to have some concrete examples showing what one can do with GenConverter which cannot be done with Converter.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions