Skip to content

Commit

Permalink
Preserve declaration order on dump (#164)
Browse files Browse the repository at this point in the history
* Preserve declaration order on dump

* Do the same w/o ordered overhead

* Ditch unused variable

* Fix typo

* Fix lint

* Add to changelog
  • Loading branch information
Pliner authored Nov 9, 2024
1 parent 8892124 commit 337894d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## unreleased

* [Preserve declaration order](https://github.com/anna-money/marshmallow-recipe/pull/164)


## v0.0.41(2024-11-01)

* [Int enum support](https://github.com/anna-money/marshmallow-recipe/pull/161)
Expand Down
9 changes: 9 additions & 0 deletions marshmallow_recipe/bake.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class _SchemaTypeKey:

_T = TypeVar("_T")
_MARSHMALLOW_VERSION_MAJOR = int(m.__version__.split(".")[0])

_schema_types: dict[_SchemaTypeKey, type[m.Schema]] = {}


Expand Down Expand Up @@ -281,6 +282,10 @@ class _Schema(m.Schema):
class Meta: # type: ignore
unknown = m.EXCLUDE # type: ignore

@property
def set_class(self) -> type:
return m.schema.OrderedSet # type: ignore

@m.post_dump
def remove_none_values(self, data: dict[str, Any], **_: Any) -> dict[str, Any]:
if none_value_handling == NoneValueHandling.IGNORE:
Expand All @@ -304,6 +309,10 @@ def pre_load(self, data: dict[str, Any], **_: Any) -> Any:

def _get_base_schema(cls: type, none_value_handling: NoneValueHandling) -> type[m.Schema]:
class _Schema(m.Schema): # type: ignore
@property
def set_class(self) -> type:
return m.schema.OrderedSet # type: ignore

@m.post_dump # type: ignore
def remove_none_values(self, data: dict[str, Any]) -> dict[str, Any]:
if none_value_handling == NoneValueHandling.IGNORE:
Expand Down
12 changes: 12 additions & 0 deletions tests/test_order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import dataclasses

import marshmallow_recipe as mr


def test_order():
@dataclasses.dataclass
class A:
a: int
b: int

assert [name for name in mr.dump(A(a=1, b=2))] == ["a", "b"]

0 comments on commit 337894d

Please sign in to comment.