Skip to content

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

@daniel-wer

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)

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