Skip to content

Inconsistent unstructuring of tuple and typing.Tuple #226

Closed

Description

@bibajz
  • cattrs version: 22.1.dev0 - 3ee4b40
  • Python version: 3.10.1
  • Operating System: irrelevant

Description

Unstructuring tuples work differently if they are annotated as tuple and typing.Tuple.

Also, unstructuring differs if the tuple is variable-length or precisely known.

What I Did

Consider these 6 classes:

import typing as t
import attrs
import cattrs

@attrs.define
class T1:
    xs: tuple

@attrs.define
class T2:
    xs: t.Tuple

@attrs.define
class T3:
    xs: tuple[int, str, float]

@attrs.define
class T4:
    xs: t.Tuple[int, str, float]

@attrs.define
class T5:
    xs: tuple[float, ...]

@attrs.define
class T6:
    xs: t.Tuple[float, ...]

Now, if you unstructure each of them, you get:

>>> converter.unstructure(T1(xs=(1, "2", 3.4)))
{'xs': [1, '2', 3.4]}
>>> converter.unstructure(T2(xs=(1, "2", 3.4)))
{'xs': (1, '2', 3.4)}


>>> converter.unstructure(T3(xs=(1, "2", 3.4)))
{'xs': (1, '2', 3.4)}
>>> converter.unstructure(T4(xs=(1, "2", 3.4)))
{'xs': (1, '2', 3.4)}


>>> converter.unstructure(T5(xs=(1, "2", 3.4)))
{'xs': [1, '2', 3.4]}
>>> converter.unstructure(T6(xs=(1, "2", 3.4)))
{'xs': [1, '2', 3.4]}

What I expected

I think you mentioned in some other issue, that unstructuring tuples into lists is more natural, since lists are supported by more languages and I agree with that, therefore I expected all the unstructurings to produce a list.


As an aside, structuring works correctly for all the cases, so a dictionary {"xs": [1, '2', 3.4]} always produces a tuple, and, in the case of T5/6, all the values are converted to float.

Activity

  1. bibajz commented on Feb 7, 2022

    @bibajz
    ContributorAuthor

    I think I can scrap some spare time this / next week, so I can look into it, if you don't want to.

    Cheers,
    Libor

  2. Tinche commented on Feb 8, 2022

    @Tinche
    Member

    What exactly are you proposing to do, make it consistent?

  3. bibajz commented on Feb 8, 2022

    @bibajz
    ContributorAuthor

    What exactly are you proposing to do, make it consistent?

    Yes, exactly, make all the unstructuring cases produce a list.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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