Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

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

Closed
layday opened this issue Jun 10, 2023 · 6 comments
Closed
Labels

Comments

@layday
Copy link
Contributor

layday commented Jun 10, 2023

  • 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?'}
@Tinche Tinche added the bug label Jun 10, 2023
@Tinche
Copy link
Member

Tinche commented Jun 10, 2023

You're right, our optional handling is very old and can be improved. Taking a look at it now.

@Tinche
Copy link
Member

Tinche commented Jun 10, 2023

This should be fixed on main now, let me know!

@Tinche Tinche closed this as completed Jun 10, 2023
@layday
Copy link
Contributor Author

layday commented Jun 11, 2023

Yep, works now, thanks.

@layday
Copy link
Contributor Author

layday commented Jun 11, 2023

Although, if I replace | None with e.g. | bool, it doesn't - not sure if that's intentional. String subclasses work with other kinds of unions.

@Tinche
Copy link
Member

Tinche commented Jun 12, 2023

Yeah we don't support any union, just a subset for now. It's tricky to do well.

@layday
Copy link
Contributor Author

layday commented Jun 12, 2023

Alright, thanks for clarifying!

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants