Skip to content

typing.NewType isn't supported #94

@rhofour

Description

@rhofour
  • cattrs version: 1.0.0
  • Python version: 3.8.5
  • Operating System: Fedora 32

Description

NewType seems to break structuring / destructuring.

Here's a minimal test case:

import unittest
from typing import NewType
import attr
import cattr

ConfigId = NewType('ConfigId', int)

@attr.s(auto_attribs=True)
class ClassWithNewTypeMember:
    configId: ConfigId

class TestAttrs(unittest.TestCase):
    def test_newType(self):

        event = ClassWithNewTypeMember(configId = ConfigId(0))
        unstructured = cattr.unstructure(event)
        structured = cattr.structure(unstructured, ClassWithNewTypeMember)

I would expect this test to pass, but instead I get the following:
E ValueError: Unsupported type: <function NewType.<locals>.new_type at 0x7fa0349398b0>. Register a structure hook for it.

The workaround is to manually register a structure hook like so:
cattr.register_structure_hook(ConfigId, lambda d, _: ConfigId(d))

A destructuring hook isn't needed.

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