Skip to content

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

Closed

Description

@daniel-wer
  • 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)

Activity

  1. added this to the 24.2 milestone on Sep 5, 2024
  2. Tinche commented on Sep 5, 2024

    @Tinche
    Member

    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.

  3. linked a pull request that will close this issueFix unstructuring literals with enums #598on Dec 12, 2024
  4. Tinche commented on Dec 12, 2024

    @Tinche
    Member

    This got fixed in the meantime!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions