python-attrs / python-attrs/cattrs
Using `typing.Any` to register a structure hook for a generic type is not working.
Open
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 1.1k
- Forks
- 159
- Avg merge
- 12h 21m
- Merged PRs (30d)
- 6
Description
- 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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the provided test_structure_generic_list reproduction with cattrs 1.0.0, focusing on register_structure_hook and cattr.structure. Trace why the GenericList[typing.Any] registration is ignored, then confirm that the Any hook handles the generic type while the existing string and integer cases still pass.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 35/100