python-attrs / cattrs

Composable custom class converters for attrs, dataclasses and friends.
https://catt.rs
MIT License
781 stars 108 forks source link

Structuring fails with PEP 695 aliases to Literal #484

Closed Fuyukai closed 6 months ago

Fuyukai commented 6 months ago

Description

Structuring a class with a type Lit = Literal[...]

What I Did

from typing import Literal

import attr
import cattr

type BootlegEnum = Literal[1, 2, 3]

@attr.s()
class UsesBootlegEnum:  # noqa: D101
    tag: BootlegEnum = attr.ib()

cattr.structure({"tag": 1}, UsesBootlegEnum)
  + Exception Group Traceback (most recent call last):
  |   File "test.py", line 13, in <module>
  |     cattr.structure({"tag": 1}, UsesBootlegEnum)
  |   File ".venv/lib/python3.12/site-packages/cattrs/converters.py", line 346, in structure
  |     return self._structure_func.dispatch(cl)(obj, cl)
  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |   File "<cattrs generated structure __main__.UsesBootlegEnum>", line 9, in structure_UsesBootlegEnum
  | cattrs.errors.ClassValidationError: While structuring UsesBootlegEnum (1 sub-exception)
  +-+---------------- 1 ----------------
    | Traceback (most recent call last):
    |   File "<cattrs generated structure __main__.UsesBootlegEnum>", line 5, in structure_UsesBootlegEnum
    |   File ".venv/lib/python3.12/site-packages/cattrs/converters.py", line 467, in _structure_simple_literal
    |     if val not in type.__args__:
    |                   ^^^^^^^^^^^^^
    | AttributeError: 'typing.TypeAliasType' object has no attribute '__args__'. Did you mean: '__ror__'?
    | Structuring class UsesBootlegEnum @ attribute tag
    +------------------------------------
Tinche commented 6 months ago

Oh interesting, good catch. Let me see if I can get this into a patch release.

Tinche commented 6 months ago

Ah sorry, I see you're on main. I forgot the type alias support is only in 24.1 which is unreleased as of yet. I will just fix this on main.

Fuyukai commented 6 months ago

Works perfectly. Thanks for the quick fix.