Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
mgrandi opened this issue Dec 13, 2019 · 2 comments
Closed

Comments

@mgrandi
Copy link

mgrandi commented Dec 13, 2019

  • 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)
@mgrandi mgrandi changed the title PEP-563 / posponed evaluation of annotations breaks loading attr classes PEP-563 (Postponed evaluation of annotations) breaks loading attr classes Dec 13, 2019
@ex-nerd
Copy link

ex-nerd commented Jan 21, 2020

Seems this is the same as #41 and submitted as PR #42. Edit: actually, looks like there are a couple PRs dealing with this issue.

@Tinche
Copy link
Member

Tinche commented Mar 21, 2021

Fixed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants