Skip to content

Support TypeAliasType for structuring #478

@declaresub

Description

@declaresub
  • cattrs version: 23.2.3
  • Python version: 3.12.0
  • Operating System: Mac OS 14.2

Structuring in cattrs supports union types represented by a TypeAlias, but not defined via type. Here's a bit of example code.

import attrs
import cattrs.preconf.json
from typing import Literal, TypeAlias

converter = cattrs.preconf.json.make_converter()
@attrs.define
class Foo:
    _type: Literal['foo'] = 'foo'

@attrs.define
class Bar:
    _type: Literal['bar'] = 'bar'

FooBar: TypeAlias = Foo | Bar

data = {'_type': 'foo'}
obj = converter.structure(data, FooBar)

This does what one expects. But the next bit raises a StructureHandlerNotFoundError.

type FooBar1 = Foo | Bar
obj = converter.structure(data, FooBar1)

It would be nice if structure also accepted TypeAliasTypes.

Even though I know better, I suggest that implementation looks straightforward -- I made this change in converters,py around line 330:


    def structure(self, obj: Any, cl: Type[T]) -> T:
        from typing import TypeAliasType

        _cl = cl
        while isinstance(_cl, TypeAliasType):
            _cl = _cl.__value__

        """Convert unstructured Python data structures to structured data."""
        return self._structure_func.dispatch(_cl)(obj, _cl)

after which I was able to structure data with type FooBar1. I note that I was unable to construct a type for which the while loop above would fail to terminate.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions