Skip to content

dict(model) errors when field name keys exists #10575

@zzstoatzz

Description

@zzstoatzz

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

A user of ours opened this issue, which appeared to show that dumping a model with dict(...) breaks if you have field on the model whose name is literally keys - which I was able to reproduce.

This error was certainly unexpected to me - I couldn't find an open or closed related issue, but apologies if I'm missing something. I couldn't immediately find a fix for this looking at BaseModel.__iter__ and a bit elsewhere, but will come back to this to try and add a fix later.

Example Code

from pydantic import BaseModel

errored = False


class A(BaseModel):
    keys: str


a = A(keys="hello")

assert a.model_dump() == {"keys": "hello"}

try:
    dict(a)
except TypeError as exc:
    errored = True
    assert "'str' object is not callable" in str(exc)
    print(f"`dict(A(keys='hello'))` errored with {exc}")

assert errored

Python, Pydantic & OS Version

             pydantic version: 2.9.2
        pydantic-core version: 2.23.4
          pydantic-core build: profile=release pgo=false
                 install path: /Users/nate/github.com/prefecthq/prefect/.venv/lib/python3.12/site-packages/pydantic
               python version: 3.12.5 (main, Aug  6 2024, 19:08:49) [Clang 15.0.0 (clang-1500.3.9.4)]
                     platform: macOS-14.6.1-arm64-arm-64bit
             related packages: fastapi-0.115.0 mypy-1.11.2 pydantic-extra-types-2.9.0 pydantic-settings-2.5.2 typing_extensions-4.12.2
                       commit: unknown

Metadata

Metadata

Assignees

No one assigned

    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