Skip to content

Don't copy dataclass methods to the schema. #79

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

Merged
merged 3 commits into from
Feb 24, 2020
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
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