nebius/SWE-rebench-V2-PRs huggingface dataset:
Repository: yukinarit/pyserde
Pull request #22 (2020-07-31 19:06:16)

Add support for pathlib.Path fields
I was missing this functionality so I added it.

Signed-off-by: Johann Fuechsl <johann@fuechsl.co>


Patch:
diff --git a/serde/more_types.py b/serde/more_types.py
index e5a0fc8..11b8509 100644
--- a/serde/more_types.py
+++ b/serde/more_types.py
@@ -3,6 +3,7 @@ Additional type support such as Decimal.
 """
 from dataclasses import Field
 from decimal import Decimal
+from pathlib import Path
 from typing import Any
 
 from .core import SerdeError
@@ -17,6 +18,8 @@ def serialize(data: Any) -> Any:
     """
     if isinstance(data, Decimal):
         return str(data)
+    elif isinstance(data, Path):
+        return str(data)
     else:
         raise SerdeError(f'Unsupported type: {type(data)}')
 
@@ -30,5 +33,7 @@ def deserialize(field: Field, data: Any) -> Any:
     """
     if issubclass(field.type, Decimal):
         return Decimal(data)
+    elif issubclass(field.type, Path):
+        return Path(data)
     else:
         raise SerdeError(f'Unsupported type: {type(data)}')


Test patch:
diff --git a/tests/test_more_types.py b/tests/test_more_types.py
index 6ca77cf..fa58503 100644
--- a/tests/test_more_types.py
+++ b/tests/test_more_types.py
@@ -1,5 +1,6 @@
 from dataclasses import dataclass
 from decimal import Decimal
+from pathlib import Path
 
 import pytest
 
@@ -14,6 +15,13 @@ class Foo:
     d: Decimal
 
 
+@deserialize
+@serialize
+@dataclass
+class Bar:
+    p: Path
+
+
 @pytest.mark.parametrize('se,de', format_json + format_yaml + format_toml)  # type: ignore
 def test_decimal(se, de):
     f = Foo(d=Decimal('0.1'))
@@ -21,3 +29,11 @@ def test_decimal(se, de):
 
     f = Foo(d=Decimal(0.1))
     assert f == de(Foo, se(f))
+
+@pytest.mark.parametrize('se,de', format_json + format_yaml + format_toml)  # type: ignore
+def test_path(se, de):
+    f = Bar(p=Path('/tmp'))
+    assert f == de(Bar, se(f))
+
+    f = Bar(p=Path('/tmp'))
+    assert f == de(Bar, se(f))
Repository: yukinarit/pyserde
Pull request #294 (2022-12-14 07:12:11)

Add support for optional unions
Fixes  #293.

Adds a check for optionals in union types (and optional unions), allowing parsing when the optional field is missing.


Patch:
diff --git a/serde/de.py b/serde/de.py
index 702f9a5..b02a9da 100644
--- a/serde/de.py
+++ b/serde/de.py
@@ -7,6 +7,7 @@ import abc
 import collections
 import dataclasses
 import functools
+import sys
 import typing
 from dataclasses import dataclass, is_dataclass
 from typing import Any, Callable, Dict, List, Optional, TypeVar
@@ -20,6 +21,7 @@ from .compat import (
     SerdeSkip,
     UserError,
     find_generic_arg,
+    get_args,
     get_generic_arg,
     get_origin,
     has_default,
@@ -515,6 +517,8 @@ class DeField(Field):
     def data(self) -> str:
         if self.iterbased:
             return f'{self.datavar}[{self.index}]'
+        elif is_union(self.type) and type(None) in get_args(self.type):
+            return f'{self.datavar}.get("{self.conv_name()}")'
         else:
             return f'{self.datavar}["{self.conv_name()}"]'
 


Test patch:
diff --git a/tests/test_union.py b/tests/test_union.py
index e6fa792..dc08c0c 100644
--- a/tests/test_union.py
+++ b/tests/test_union.py
@@ -52,6 +52,16 @@ class PriOptUnion:
     v: Union[Optional[int], Optional[str], Optional[float], Optional[bool]]
 
 
+@serde
+@dataclass(unsafe_hash=True)
+class OptionalUnion:
+    """
+    Union Primitives.
+    """
+
+    v: Optional[Union[int, str]]
+
+
 @serde
 @dataclass(unsafe_hash=True)
 class ContUnion:
@@ -120,6 +130,9 @@ def test_union_optional():
     assert s == to_json(v)
     assert v == from_json(PriOptUnion, s)
 
+    assert PriOptUnion(None) == from_json(PriOptUnion, '{}')
+    assert OptionalUnion(None) == from_json(OptionalUnion, '{}')
+
 
 def test_union_containers():
     v = ContUnion([1, 2, 3])
Repository: yukinarit/pyserde
Pull request #438 (2023-10-23 20:22:51)

Fix frozenset union with prim #437
Proposed fix for #437 


Patch:
diff --git a/serde/core.py b/serde/core.py
index 344c61b..63449e2 100644
--- a/serde/core.py
+++ b/serde/core.py
@@ -413,7 +413,7 @@ def is_list_instance(obj: Any, typ: Type[Any]) -> bool:
 
 
 def is_set_instance(obj: Any, typ: Type[Any]) -> bool:
-    if not isinstance(obj, set):
+    if not isinstance(obj, (set, frozenset)):
         return False
     if len(obj) == 0 or is_bare_set(typ):
         return True


Test patch:
diff --git a/tests/test_union.py b/tests/test_union.py
index d51b468..af02d6d 100644
--- a/tests/test_union.py
+++ b/tests/test_union.py
@@ -2,7 +2,7 @@ import logging
 import sys
 from dataclasses import dataclass
 from ipaddress import IPv4Address
-from typing import Dict, Generic, List, NewType, Optional, Tuple, TypeVar, Union
+from typing import Dict, FrozenSet, Generic, List, NewType, Optional, Tuple, TypeVar, Union
 from uuid import UUID
 
 import pytest
@@ -763,3 +763,12 @@ def test_union_directly() -> None:
     # untagged tagged
     s = to_json(bar, cls=Untagged(Union[Foo, Bar]))
     assert bar == from_json(Untagged(Union[Foo, Bar]), s)
+
+
+def test_union_frozenset_with_prim():
+    @serde
+    @dataclass
+    class Foo:
+        a: Union[FrozenSet[int], int]
+
+    assert to_dict(Foo(frozenset({1}))) == {"a": {1}}
Repository: yukinarit/pyserde
Pull request #504 (2024-03-30 16:11:35)

Raises SerdeError when type validation fails
pyserde uses beartype v0.17 new feature to customize exception for type validation failure.

One caveat is when class already implements beartype decorator before serde as below, pyserde cannot set custom exception. In this case, beartype's exception is raised.

```python
@serde
@beartype
@dataclass
class Foo:
    ...
```


Patch:
diff --git a/serde/de.py b/serde/de.py
index 8af6ced..3b20592 100644
--- a/serde/de.py
+++ b/serde/de.py
@@ -11,8 +11,8 @@ import dataclasses
 import functools
 import typing
 import jinja2
-import beartype
 from collections.abc import Callable, Sequence, Iterable
+from beartype import beartype, BeartypeConf
 from beartype.roar import BeartypeCallHintParamViolation
 from dataclasses import dataclass, is_dataclass
 from typing import overload, TypeVar, Generic, Any, Optional, Union, Literal
@@ -223,7 +223,8 @@ def deserialize(
             dataclass(cls)
 
         if type_check.is_strict():
-            beartype.beartype(cls)
+            serde_beartype = beartype(conf=BeartypeConf(violation_type=SerdeError))
+            serde_beartype(cls)
 
         g: dict[str, Any] = {}
 
diff --git a/serde/se.py b/serde/se.py
index 72274be..5962a0a 100644
--- a/serde/se.py
+++ b/serde/se.py
@@ -10,11 +10,11 @@ import dataclasses
 import functools
 import typing
 import itertools
-import beartype
 import jinja2
 from dataclasses import dataclass, is_dataclass
 from typing import TypeVar, Literal, Generic, Optional, Any, Union
 from collections.abc import Callable, Iterable, Iterator
+from beartype import beartype, BeartypeConf
 from beartype.door import is_bearable
 from typing_extensions import dataclass_transform
 
@@ -198,7 +198,8 @@ def serialize(
             dataclass(cls)
 
         if type_check.is_strict():
-            beartype.beartype(cls)
+            serde_beartype = beartype(conf=BeartypeConf(violation_type=SerdeError))
+            serde_beartype(cls)
 
         g: dict[str, Any] = {}
 


Test patch:
diff --git a/tests/test_beartype.py b/tests/test_beartype.py
new file mode 100644
index 0000000..173a02a
--- /dev/null
+++ b/tests/test_beartype.py
@@ -0,0 +1,26 @@
+import pytest
+from beartype import beartype
+from beartype.roar import BeartypeCallHintParamViolation
+from dataclasses import dataclass
+from serde import serde, SerdeError
+
+
+def test_raises_serde_error_instead_of_beartype_error() -> None:
+    @serde
+    class Foo:
+        v: int
+
+    with pytest.raises(SerdeError):
+        Foo("foo")  # type: ignore
+
+
+def test_raises_beartype_error_if_beartype_decorated() -> None:
+    # If a class already has beartype, pyserde cannot set custom validation error.
+    @serde
+    @beartype
+    @dataclass
+    class Foo:
+        v: int
+
+    with pytest.raises(BeartypeCallHintParamViolation):
+        Foo("foo")  # type: ignore