Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dataclasses: fix kwonly arg recognition #638

Merged
merged 1 commit into from
Mar 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# History

```{currentmodule} cattrs

```

This project adheres to [Calendar Versioning](https://calver.org/).
Expand All @@ -9,6 +11,11 @@ The third number is for emergencies when we need to start branches for older rel

Our backwards-compatibility policy can be found [here](https://github.com/python-attrs/cattrs/blob/main/.github/SECURITY.md).

## 24.1.3 (UNRELEASED)

- Fix structuring of keyword-only dataclass fields when not using detailed validation.
([#637](https://github.com/python-attrs/cattrs/issues/637) [#638](https://github.com/python-attrs/cattrs/pull/638))

## 24.1.2 (2024-09-22)

- Fix {meth}`BaseConverter.register_structure_hook` and {meth}`BaseConverter.register_unstructure_hook` type hints.
Expand Down
1 change: 1 addition & 0 deletions src/cattrs/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ def adapted_fields(cl) -> List[Attribute]:
True,
type=type_hints.get(attr.name, attr.type),
alias=attr.name,
kw_only=getattr(attr, "kw_only", False),
)
for attr in attrs
]
Expand Down
20 changes: 20 additions & 0 deletions tests/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
from typing import List

import attr
import pytest

from cattrs import BaseConverter

from ._compat import is_py310_plus


@dataclasses.dataclass
class Foo:
Expand Down Expand Up @@ -41,3 +44,20 @@ def test_dataclasses(converter: BaseConverter):

assert converter.unstructure(struct) == unstruct
assert converter.structure(unstruct, Foo) == struct


@pytest.mark.skipif(not is_py310_plus, reason="kwonly fields are Python 3.10+")
def test_kw_only_propagation(converter: BaseConverter):
"""KW-only args work.

Reproducer from https://github.com/python-attrs/cattrs/issues/637.
"""

@dataclasses.dataclass
class PartialKeywords:
a1: str = "Default"
a2: str = dataclasses.field(kw_only=True)

assert converter.structure({"a2": "Value"}, PartialKeywords) == PartialKeywords(
a1="Default", a2="Value"
)