Skip to content

Unstructure hook for NewType not invoked if NewType appears in a union #380

@layday

Description

@layday
  • cattrs version: 23.1.2
  • Python version: 3.11
  • Operating System: macOS

Description

NewType unstructure hooks are not invoked if the new type appears in a union with other types.

What I Did

from typing import NewType

from attr import define
from cattr import Converter

Foo = NewType('Foo', str)

converter = Converter()
converter.register_unstructure_hook(Foo, lambda v: v.replace("foo", "bar"))

@define
class ModelWithFoo:
    total_foo: Foo
    maybe_foo: Foo | None

print(converter.unstructure(ModelWithFoo(Foo("foo"), Foo("is it a foo?"))))
# Produces: {'total_foo': 'bar', 'maybe_foo': 'is it a foo?'}

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