python-attrs / python-attrs/cattrs

kw_only tuple support?

Open
#234 12 comments 0 reactions 0 assignees View on GitHub

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.10.0
  • Python version: 3.10.2
  • Operating System: macOS
Description

I have a nested data structure using attrs and kw_only. Converting to a tuple works beautifully, letting me load this structure into a SQLite3 database.

import attrs
import cattrs

@attrs.define(kw_only=True)
class A:
    a: str = ""

@attrs.define(kw_only=True)
class B(A):
    b: int

# PS: The reason for kw_only is primarily because it makes subclassing work properly
# for building data structures with arbitrary defaults - the above requires
# kw_only in either attrs or Python 3.10's dataclasses.

converter = cattrs.GenConverter()
converter.unstructure_attrs_astuple(B(b=2)) # -> ('', 2)

However, the other direction fails:

>>> converter.structure_attrs_fromtuple(('', 2), B)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/henryschreiner/git/CMS/hypernewsviewer/.venv/lib/python3.10/site-packages/cattr/converters.py", line 424, in structure_attrs_fromtuple
    return cl(*conv_obj)  # type: ignore
TypeError: B.__init__() takes 1 positional argument but 3 were given

My current workaround is a little ugly and possibly not very efficient:

>>> converter.structure_attrs_fromdict({n.name:i for n,i in zip(attrs.fields(B), ('', 2))}, B)
B(a='', b=2) 

Would it be possible to make fromtuple work on a kw_only class, like astuple does? IMO, kw_only is about subclassing & controlling manual creation, not raw conversion.

Might be hard/impossible, but thought I'd ask.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in cattr/converters.py at structure_attrs_fromtuple, then compare it with unstructure_attrs_astuple and the structure_attrs_fromdict workaround shown in the issue. Reproduce the B example with Python 3.10 and attrs kw_only classes. Done means tuple conversion constructs B(a='', b=2) without passing positional arguments, with tests covering the nested inheritance case.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.