Skip to content

Using typing.Any to register a structure hook for a generic type is not working. #87

Open
@diefans

Description

@diefans
  • cattrs version: 1.0.0
  • Python version: 3.8.2
  • Operating System: archlinux

Description

import typing

import attr
import cattr
import typing_inspect


T = typing.TypeVar("T")


class GenericList(typing.List[T]):
    ...


def _structure_generic_list(d, t):
    (conv,) = typing_inspect.get_args(t)
    return list(map(conv, d.split(",")))

# this is ignored
cattr.register_structure_hook(GenericList[typing.Any], _structure_generic_list)

# this works
cattr.register_structure_hook(GenericList[str], _structure_generic_list)
cattr.register_structure_hook(GenericList[int], _structure_generic_list)


@attr.s(auto_attribs=True)
class Params:
    some_words: GenericList[str]
    some_ids: GenericList[int]


def test_structure_generic_list():
    src = {"some_words": "foo,bar", "some_ids": "123,456"}
    params = cattr.structure(src, Params)
    assert params == Params(some_words=["foo", "bar"], some_ids=[123, 456])

Using typing.Any to register a structure hook for a generic type is not working.

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