Skip to content

Option to include init=False globally on a converter, not per class #482

Open
@MicaelJarniac

Description

@MicaelJarniac
  • cattrs version: v23.2.3
  • Python version: 3.11.6
  • Operating System: Ubuntu

Description

On previous cattrs versions, I used to structure and unstructure a lot of attrs classes that had many init=False fields.

Now, though, with the new versions of cattrs (v23.2.0), this behavior changed, breaking my code.

I'd like to be able to enable the old behavior back globally on a converter, instead of having to enable it for every single class, as I have many classes all over the place that would benefit from re-enabling init=False fields in conversion.

import attrs
import cattrs


@attrs.define
class Foo:
    bar: int
    baz: str = attrs.field(init=False)


foo = Foo(bar=1)
foo.baz = "hello"


converter = cattrs.Converter()
print(converter.unstructure(foo))
# before: {'bar': 1, 'baz': 'hello'}
# after: {'bar': 1}

I thought about something like this:

import cattrs
from cattrs.strategies import include_init_false

converter = cattrs.Converter()
include_init_false(converter)

# OR

converter = cattrs.Converter(include_init_false=True)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions