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

Different behavior for extra_behavior and config.extra_fields_behavior #1243

Open
sydney-runkle opened this issue Mar 21, 2024 · 2 comments
Open
Assignees
Labels
bug Something isn't working

Comments

@sydney-runkle
Copy link
Member

See #1236 (comment) for a more in depth description :)

@sydney-runkle sydney-runkle self-assigned this Mar 21, 2024
@sydney-runkle sydney-runkle added bug Something isn't working and removed unconfirmed labels Aug 16, 2024
@sydney-runkle
Copy link
Member Author

The problem here being that these two different ways of specifying extra_behavior result in different results:

from pydantic_core import core_schema, SchemaValidator, SchemaSerializer

class Parent:
    x: int

class Other(Parent):
    y: str

Parent.__pydantic_core_schema__ = core_schema.model_schema(
    Parent,
    core_schema.model_fields_schema(
        {
            'x': core_schema.model_field(core_schema.int_schema()),
        }
    ),
    extra_behavior='allow',
    # config=core_schema.CoreConfig(extra_behavior='allow'),
)
Parent.__pydantic_validator__ = SchemaValidator(Parent.__pydantic_core_schema__)
Parent.__pydantic_serializer__ = SchemaSerializer(Parent.__pydantic_core_schema__)

Other.__pydantic_core_schema__ = core_schema.model_schema(
    Other,
    core_schema.model_fields_schema(
        {
            'x': core_schema.model_field(core_schema.int_schema()),
            'y': core_schema.model_field(core_schema.str_schema()),
        }
    ),
    extra_behavior='forbid',
    # config=core_schema.CoreConfig(extra_behavior='forbid'),
)
Other.__pydantic_validator__ = SchemaValidator(Other.__pydantic_core_schema__)
Other.__pydantic_serializer__ = SchemaSerializer(Other.__pydantic_core_schema__)

other = Other.__pydantic_validator__.validate_python({'x': 1, 'y': 'some string'})
assert Parent.__pydantic_serializer__.to_python(other) == {'x': 1}

@sydney-runkle
Copy link
Member Author

So, the problem is resolved here if you set extra_behavior on both the model and model_fields schemas - should that be the case, or should the model schema push down that setting?

cc @davidhewitt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants