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

Preserve declaration order on dump #164

Merged
merged 6 commits into from
Nov 9, 2024
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
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"]
Loading