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

Children schema doesn't get parent init values #86

Open
jgourinda opened this issue Jun 10, 2019 · 1 comment
Open

Children schema doesn't get parent init values #86

jgourinda opened this issue Jun 10, 2019 · 1 comment

Comments

@jgourinda
Copy link

When using a parent schema the initialization value do get passed to the actual children schema.
Use case: I want to be able to bypass the classic post_load make_object when I init a partial schema.

    @post_load
    def make_object(self, data: Dict) -> object:
        if self.__model__ is None or self.partial:
            return data
        return self.__model__(**data)

The problem is that if a use a parent OneOfSchema the final schema is instantiated withou any init parameters. See here and here in marshmallowoneofschema/marshmallow_oneofschema/one_of_schema.py

schema = type_schema if isinstance(type_schema, Schema) else type_schema()
@kevinadda
Copy link

kevinadda commented Jul 8, 2019

There is a pull request for that, but it is 1 year old and has conflicts : #15

Problem in this PR is that arguments cannot be passed to both the child class and parent class constructor. For instance parameter only would trigger an exception since the parent schema has no field.

One simple workaround is to wrap type_schema in a method that takes care of child schema initialization, in the parent constructor. Here is what I do:

from marshmallow_oneofschema import OneOfSchema

class ExtendedOneOfSchema(OneOfSchema):
    def __init__(self, *args, **kwargs):
        self._schema_args = args
        self._schema_kwargs = kwargs

        # Wrap schema initialization to add arguments
        self.type_schemas = {
            k: self.with_args(v) for k, v in self.type_schemas.items()
        }

        super(ExtendedOneOfSchema, self).__init__()

    def with_args(self, schema):
        def init_schema():
            return schema(*self._schema_args, **self._schema_kwargs)
        return init_schema

This works well for me, I'm not sure it generalizes well.

I'll be happy to create a PR for this if it is of any interest.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants