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

Union type coercion with defaults results in unexpected behavior #7223

Open
1 task done
Narquadah opened this issue Aug 23, 2023 · 1 comment
Open
1 task done

Union type coercion with defaults results in unexpected behavior #7223

Narquadah opened this issue Aug 23, 2023 · 1 comment
Assignees
Labels
bug V2 Bug related to Pydantic V2

Comments

@Narquadah
Copy link

Narquadah commented Aug 23, 2023

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

When using type coercion with a union and defaults, pydantic chooses the first type rather the one where a value has been set.

For now I am using validators as a workaround.

Example Code

from pydantic import BaseModel, TypeAdapter

class A(BaseModel):
    field_a: str | None = None


class B(BaseModel):
    field_b: str | None = None

United = A | B

instance_a = TypeAdapter(United).validate_python({'field_a': 'test'})
instance_b = TypeAdapter(United).validate_python({'field_b': 'test'})
print(isinstance(instance_a, A)) # True
print(isinstance(instance_b, B)) # False

Python, Pydantic & OS Version

pydantic version: 2.2.1
        pydantic-core version: 2.6.1
          pydantic-core build: profile=release pgo=false
                 install path: /Users/<user>/Library/Caches/pypoetry/virtualenvs/frogcloud-daemon-kMv5m2mx-py3.11/lib/python3.11/site-packages/pydantic
               python version: 3.11.2 (main, Feb 20 2023, 11:40:31) [Clang 14.0.0 (clang-1400.0.29.202)]
                     platform: macOS-13.5-arm64-arm-64bit
     optional deps. installed: ['email-validator', 'typing-extensions']

Selected Assignee: @davidhewitt

@Narquadah Narquadah added bug V2 Bug related to Pydantic V2 unconfirmed Bug not yet confirmed as valid/applicable labels Aug 23, 2023
@davidhewitt
Copy link
Contributor

You can workaround the situation here by setting extra = 'forbid' in your model configuration. What is happening is that the A type is ignoring the field for B and then successfully validates by using the defaults.

I agree this is not ideal, and I've been working on improvements to union type inference in pydantic/pydantic-core#867. I think the changes I have in mind would not solve this case.

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

No branches or pull requests

2 participants