Skip to content

PEP-563 (Postponed evaluation of annotations) breaks loading attr classes #80

@mgrandi

Description

@mgrandi
  • cattrs version: 0.9.0
  • Python version: 3.8
  • Operating System: windows

Description

It appears that when you have attr classes that are in a file with from __future__ import annotations, cattrs does not work when trying to structure a simple type to your attrs class. This is because attrs uses __annotations__ to get the type annotations and with PEP-563, these are now strings instead of the actual type, see python-attrs/attrs#288 (comment) for a description

This little script below demonstrates the problem. If you comment out the first line, the from __future__ import annotations, it works, but if you put it back, you get a ValueError because the type that cattr passed to functools.singledispatch is a string of the type, not the type itself.

from __future__ import annotations

import attr
import cattr

@attr.s
class Item:
    desc:str = attr.ib()

@attr.s
class Box:
    itemone:Item = attr.ib()
    itemtwo:Item = attr.ib()

x = Item("pencil")
y = Item("pen")
box = Box(x,y)

c = cattr.Converter()
c.register_structure_hook(Box, c.structure_attrs_fromdict)
c.register_structure_hook(Item, c.structure_attrs_fromdict)

unstructured = c.unstructure(box)

print(unstructured)

structured = c.structure(unstructured, Box)

print(structured)

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