cattrs: [bug][1.2] unstructure hook not applied when use 'from __future__ import annotations'

version: cattrs==1.2; python: 3.8

Hi, the test code as below, if uncomment first line, test failed. And I really need ‘from future import annotations’ for my mypy checking in somewhere.

Another issue is mypy checking error on the same code below, such as: error: Cannot infer type argument 1 of “register_unstructure_hook” of “Converter”

# from __future__ import annotations  # uncomment this line test will fail

from datetime import datetime
import cattr
from attr import attrs, ib

@attrs
class TestData:
    dt: datetime = ib()

converter = cattr.Converter()
converter.register_unstructure_hook(datetime,
                                    lambda val: val.strftime('%Y-%m-%d %H:%M:%S')
                                    if val is not None else None)

data = TestData(datetime.now())

result = converter.unstructure(data)

print(type(result.get('dt')))
assert type(result.get('dt')) == str

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 20 (15 by maintainers)

Commits related to this issue

Most upvoted comments

I’m kind of letting folks test it out in the wild for the time being. I would say the release after the next one will be 2.0 and have the GenConverter be the default converter.

@sobolevn Try this:

from __future__ import annotations

from typing import List

import attr

import cattr

c = cattr.GenConverter()


@attr.dataclass(slots=True, frozen=True)
class Some(object):
    a: List[str]


print(c.structure({"a": ["1", "2", "3"]}, Some))

The GenConverter will become the default in a few versions. This is difficult to do in the legacy converter due to performance concerns.