Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Collections.abc types do not work like typing types #128

Closed
Dr-ZeeD opened this issue Mar 8, 2021 · 4 comments
Closed

Collections.abc types do not work like typing types #128

Dr-ZeeD opened this issue Mar 8, 2021 · 4 comments

Comments

@Dr-ZeeD
Copy link

Dr-ZeeD commented Mar 8, 2021

  • cattrs version: 1.3.0
  • Python version: Python 3.9.1
  • Operating System: macOS 11.2.1

Description

Python 3.9 deprecated typing.<containers> in favor of using collections.abc.<containers>. Using collections.abc. containers does not work as expected, though.

What I Did

from collections import abc
import typing

from attr import define

from cattr import GenConverter


@define
class A:
    a: int


@define
class B:
    b: typing.MutableSequence[A]


@define
class C:
    c: abc.MutableSequence[A]


converter = GenConverter()


if __name__ == "__main__":
    a = A(1)

    b = B([a])
    print(converter.unstructure(b))

    c = C([a])
    print(converter.unstructure(c))

The actual output is:

{'b': [{'a': 1}]}
{'c': [A(a=1)]}

What I expected:

{'b': [{'a': 1}]}
{'c': [{'a': 1}]}
@Dr-ZeeD
Copy link
Author

Dr-ZeeD commented Mar 8, 2021

Also note that introducing a unstructure hook via

converter.register_unstructure_hook(
    abc.MutableSequence,
    partial(converter.unstructure, unstructure_as=typing.MutableSequence),
)

does not lead to the desired result.

However, somewhat similarly to the other issue I had raise, this might be a viable short term fix:

def _is_sequence(cls):
    return issubclass(get_origin(cls), abc.Sequence)


converter.register_unstructure_hook_func(_is_sequence, converter._unstructure_seq)
converter.register_structure_hook_func(_is_sequence, converter._structure_list)

@Tinche
Copy link
Member

Tinche commented Mar 8, 2021

If the typing alternatives are deprecated with is worth fixing quickly. Will look into it over the next couple of days.

@Tinche
Copy link
Member

Tinche commented Mar 9, 2021

Should be fixed in Tinche@da63135

@Dr-ZeeD
Copy link
Author

Dr-ZeeD commented Mar 9, 2021

Works like a charm. Thank you! Let me apologize in advance, I am currently formulating a new issue 😅

@Dr-ZeeD Dr-ZeeD closed this as completed Mar 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants