Skip to content

Commit

Permalink
Don't copy dataclass methods to the schema.
Browse files Browse the repository at this point in the history
  • Loading branch information
python-desert authored Feb 24, 2020
2 parents 1a44f59 + 0c9d39e commit 6b073af
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
1 change: 1 addition & 0 deletions changelog.d/79.change.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Schemas no longer copy non-field dataclass attributes. Thanks to @sveinse for report and test.
8 changes: 5 additions & 3 deletions src/desert/_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,12 @@ def class_schema(
else:
raise desert.exceptions.NotAnAttrsClassOrDataclass(clazz)

# Copy all public members of the dataclass to the schema
attributes = {k: v for k, v in inspect.getmembers(clazz) if not k.startswith("_")}
# Update the schema members to contain marshmallow fields instead of dataclass fields
# Copy all public fields of the dataclass to the schema
attributes = {
field.name: field for field in fields if not field.name.startswith("_")
}

# Update the schema members to contain marshmallow fields instead of dataclass fields.
hints = t.get_type_hints(clazz)
for field in fields:
if field.init:
Expand Down
14 changes: 14 additions & 0 deletions tests/test_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,3 +557,17 @@ def _(self):

schema = desert.schema(C)
assert schema.load({"x": 1}) == C(x=1, y=2)


def test_methods_not_on_schema(module):
"""Dataclass methods are not copied to the schema."""

@module.dataclass
class A:
def dataclass_method(self) -> None:
"""This method should not exist on the schema."""

schema = desert.schema(A)
sentinel = object()
method = getattr(schema, "dataclass_method", sentinel)
assert method is sentinel

0 comments on commit 6b073af

Please sign in to comment.