Skip to content

setattr does not add extra field to model_extra (i.e. __pydantic_extra__) #6333

@aaraney

Description

@aaraney

Initial Checks

  • I confirm that I'm using Pydantic V2 installed directly from the main branch, or equivalent

Description

First off, I may have missed this in the migration guide, so my apologies if I missed this change there.

In Pydantic V1 if extra fields are allowed (extra="allow"), setting a non-field attribute on a model instance (m.extra_field = "extra_value") adds the extra field to __dict__ and thus the extra field is included in dict() and json() outputs. I would not expect in Pydantic V2 that the extra field would be set on __dict__, but instead __pydantic_extra__. However, this is not the case. So, any extra fields set by attribute (i.e. as above or setattr(m, "extra_field", "extra_value") are not included in model_dump() or model_dump_json().

Example Code

from pydantic import BaseModel, ConfigDict


class Foo(BaseModel):
    model_config  = ConfigDict(extra="allow")

foo = Foo()
foo.extra_field = "extra_value"
assert "extra_field" not in foo.model_dump()

Python, Pydantic & OS Version

pydantic version: 2.0
        pydantic-core version: 2.0.1 release build profile
                 install path: ~/home/user/venv/lib/python3.9/site-packages/pydantic
               python version: 3.9.16 (main, Mar 24 2023, 12:31:28)  [Clang 14.0.0 (clang-1400.0.29.202)]
                     platform: macOS-13.2.1-arm64-arm-64bit
     optional deps. installed: ['typing-extensions']

Selected Assignee: @samuelcolvin

Metadata

Metadata

Assignees

Labels

bug V2Bug related to Pydantic V2pendingIs unconfirmed

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions