Skip to content

Commit

Permalink
Fix regression (#454)
Browse files Browse the repository at this point in the history
* Fix regression

* Run CI on every PR
  • Loading branch information
Tinche committed Nov 20, 2023
1 parent c098cd8 commit 281f324
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 5 deletions.
5 changes: 2 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ on:
push:
branches: ["main"]
pull_request:
branches: ["main"]
workflow_dispatch:

jobs:
Expand Down Expand Up @@ -47,7 +46,7 @@ jobs:

steps:
- uses: "actions/checkout@v3"

- uses: "actions/setup-python@v4"
with:
cache: "pip"
Expand Down Expand Up @@ -76,7 +75,7 @@ jobs:
with:
name: "html-report"
path: "htmlcov"

- name: "Make badge"
if: github.ref == 'refs/heads/main'
uses: "schneegans/dynamic-badges-action@v1.4.0"
Expand Down
5 changes: 5 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# History

## 23.2.2 (UNRELEASED)

- Fix a regression when unstructuring `Any | None`.
([#453](https://github.com/python-attrs/cattrs/issues/453))

## 23.2.1 (2023-11-18)

- Fix unnecessary `typing_extensions` import on Python 3.11.
Expand Down
7 changes: 6 additions & 1 deletion src/cattrs/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,12 @@ def gen_unstructure_optional(self, cl: Type[T]) -> Callable[[T], Any]:
"""Generate an unstructuring hook for optional types."""
union_params = cl.__args__
other = union_params[0] if union_params[1] is NoneType else union_params[1]
handler = self._unstructure_func.dispatch(other)

# TODO: Remove this special case when we make unstructuring Any consistent.
if other is Any:
handler = self.unstructure
else:
handler = self._unstructure_func.dispatch(other)

def unstructure_optional(val, _handler=handler):
return None if val is None else _handler(val)
Expand Down
14 changes: 13 additions & 1 deletion tests/test_optionals.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from typing import NewType, Optional
from typing import Any, NewType, Optional

import pytest
from attrs import define

from cattrs import Converter

from ._compat import is_py310_plus


Expand Down Expand Up @@ -39,3 +41,13 @@ class ModelWithFoo:
"total_foo": "bar",
"maybe_foo": "is it a bar?",
}


def test_optional_any(converter: Converter):
"""Unstructuring Any|None is equivalent to unstructuring as v.__class__."""

@define
class A:
pass

assert converter.unstructure(A(), Optional[Any]) == {}

0 comments on commit 281f324

Please sign in to comment.