Skip to content

can't structure dataclass with PEP563 postponed annotations or forward references #195

@anthrotype

Description

@anthrotype
  • cattrs version: 1.8.0
  • Python version: 3.10.0
  • Operating System: macOS 12.0.1

Description

I would like to use cattrs with dataclasses (for this project I can't use attrs classes). I get the following errors when I try to structure a dataclass with circular, nested definitions that contain string literals to be post-evaluated (e.g. via typing.get_type_hints).
It seems that this currently only works with attrs classes, but not dataclasses.

What I Did

from __future__ import annotations
from typing import List
from dataclasses import dataclass, field
from cattr import Converter, GenConverter


@dataclass
class Node:
    children: List[Node] = field(default_factory=list)


tree = Node([Node([Node(), Node()]), Node()])

c = GenConverter()
data = c.unstructure(tree)
# Raises: NotAnAttrsClassError: <class '__main__.Node'> is not an attrs-decorated class.
c.structure(data, Node)


c = Converter()
data = c.unstructure(tree)
# Raises: StructureHandlerNotFoundError: Unsupported type: List[Node]. Register a structure hook for it.
c.structure(data, Node)

If I remove from __future__ import annotations and type the nested children: List["Node"] I get this other error:

StructureHandlerNotFoundError: Unsupported type: ForwardRef('Node'). Register a structure hook for it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions