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

Unstructuring of enum.Enum instances in typing.Literal types doesn't work #321

Open
daniel-wer opened this issue Nov 10, 2022 · 1 comment
Milestone

Comments

@daniel-wer
Copy link

  • cattrs version: 22.2.0
  • Python version: 3.9.13
  • Operating System: Ubuntu 20.04.1

Description

I was glad to see #231 which fixes the structuring of enum.Enum instances in typing.Literal types. However, the unstructuring doesn't work yet. See this example (adapted from #231).

What I Did

import attr, cattrs, enum
from typing import Literal

class A(enum.Enum):
    BLA = 1

@attr.define
class Works:
    a: A

@attr.define
class Broken:
    a: Literal[A.BLA]

print(cattrs.unstructure(cattrs.structure({"a": 1}, Works)))   # {'a': 1}
print(cattrs.unstructure(cattrs.structure({"a": 1}, Broken)))  # {'a': <A.BLA: 1>}

My temporary fix is rather straightforward, but it would be great if cattrs would work for this out of the box:

import cattrs
from typing import Literal, get_origin

_c = cattrs.GenConverter()
_c.register_unstructure_hook_func(lambda v: get_origin(v) is Literal, _c.unstructure)
@Tinche
Copy link
Member

Tinche commented Sep 5, 2024

Sorry, for whatever reason I forgot to leave a comment when you created the issue.

You're right, I'll get this fixed for the next version.

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