Skip to content

IndexError: tuple index out of range when unstructure dataclass with typing.List annotation #209

Closed
@DriverX

Description

@DriverX
  • cattrs version: 1.10.0
  • Python version: 3.8.12
  • Operating System: Centos

Description

Got IndexError: tuple index out of range error when unstructure dataclass with only List attribute annotation.

What I Did

import attr
from typing import List
import cattr


@attr.s(slots=True, kw_only=True)
class A:
    texts: List = attr.ib()


print(cattr.unstructure(A(texts=[])))

Got exceeption

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print(cattr.unstructure(A(texts=[])))
  File "python3.8/site-packages/cattr/converters.py", line 197, in unstructure
    return self._unstructure_func.dispatch(
  File "python3.8/site-packages/cattr/dispatch.py", line 49, in _dispatch
    return self._function_dispatch.dispatch(cl)
  File "python3.8/site-packages/cattr/dispatch.py", line 126, in dispatch
    return handler(typ)
  File "python3.8/site-packages/cattr/converters.py", line 722, in gen_unstructure_attrs_fromdict
    h = make_dict_unstructure_fn(
  File "python3.8/site-packages/cattr/gen.py", line 125, in make_dict_unstructure_fn
    handler = converter._unstructure_func.dispatch(t)
  File "python3.8/site-packages/cattr/dispatch.py", line 49, in _dispatch
    return self._function_dispatch.dispatch(cl)
  File "python3.8/site-packages/cattr/dispatch.py", line 126, in dispatch
    return handler(typ)
  File "python3.8/site-packages/cattr/converters.py", line 754, in gen_unstructure_iterable
    h = make_iterable_unstructure_fn(
  File "python3.8/site-packages/cattr/gen.py", line 339, in make_iterable_unstructure_fn
    type_arg = get_args(cl)[0]
IndexError: tuple index out of range

Replace List -> List[Any] or List -> Optional[List] fix this problem.

import attr
from typing import List, Optional
import cattr


@attr.s(slots=True, kw_only=True)
class A:
    texts: Optional[List] = attr.ib()


print(cattr.unstructure(A(texts=[])))

Produce correct result

{'texts': []}

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