marshmallow-code / marshmallow-code/marshmallow

Excluding a field using Meta.exclude in a base class

Open
#1,578 0 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
Python
Stars
7.2k
Forks
738
Avg merge
1d 23h
Merged PRs (30d)
7

Description

Since #826, because the check also applies on Meta parameters, this fails because there is no `"bar"` field in the schema:

```py
class MySchema(Schema):
foo = fields.Field()

class Meta:
exclude = ('bar', )

MySchema()
```

In my app, I would like to exclude a field from all schemas, so I'd like to add `exclude=field_name` to my base schema class. But since the field is not in all schemas, it fails on the ones that don't contain the field.

I do this as a workaround, but it sucks:

```py
class BaseSchema(Schema):
def _init_fields(self):
super()._init_fields()
self.fields.pop('field_name', None)
self.load_fields.pop('field_name', None)
self.dump_fields.pop('field_name', None)
```

Any ideas how to do this correctly?

Maybe this check is too restrictive after all.

Contributor guide

Open the contributing guide

Research direction

Start by tracing Schema._init_fields and the handling of Meta.exclude, using the example with an absent "bar" field to reproduce the failure. Compare that behavior with the BaseSchema workaround; done means a base-class exclusion can be inherited by schemas that do not define the excluded field without raising an error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.