Skip to content

NamedTuple to dictionary serialization #425

@karlicoss

Description

@karlicoss
  • cattrs version: 23.1.2
  • Python version: 3.10
  • Operating System: Ubuntu 22.04

Description

For my project, cachew, I've been trying to switch from using my custom serialization cold to some existing library.
After some evaluation, cattrs seems like the most promising since it works so well with python typing annotations.
One thing that stops me is that seems like it doesn't support NamedTuple? I feel like it should be treated just like a @dataclass, but seems like cattrs just treats them as 'unknown' types and leaves intact.

What I Did

This is kinda the minimal snippet that shows the issue:

from dataclasses import dataclass
from typing import NamedTuple

import cattrs

@dataclass
class D:
    value: int


class N(NamedTuple):
    value: int


und = cattrs.unstructure(D(value=123), D)
unn = cattrs.unstructure(N(value=123), N)

print(und, type(und))
print(unn, type(unn))

The result is

{'value': 123} <class 'dict'>
N(value=123) <class '__main__.N'>

So the dataclass is serialized just as expected, but the namedtuple is just left intact.

I searched in cattrs source code, and it seems like NamedTuple isn't mentioned at all -- so perhaps it was just forgotten rather than deliberately left out?
I know I can implement a custom adapter, but feels like it makes sense to have them treated as dataclasses by default?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions