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 types don't recognize bools in coercion order if ints or floats are included #2701

Closed
3 tasks done
dlopuch opened this issue Apr 26, 2021 · 1 comment
Closed
3 tasks done
Labels
bug V1 Bug related to Pydantic V1.X

Comments

@dlopuch
Copy link

dlopuch commented Apr 26, 2021

Checks

  • I added a descriptive title to this issue
  • I have searched (google, github) for similar issues and couldn't find anything
  • I have read and followed the docs and still think this is a bug

Bug

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.8.1
            pydantic compiled: True
                 install path: ~/.local/share/virtualenvs/XXX-D1SziJ_u/lib/python3.6/site-packages/pydantic
               python version: 3.6.13 (default, Feb 18 2021, 16:38:18)  [GCC Apple LLVM 12.0.0 (clang-1200.0.32.29)]
                     platform: Darwin-20.3.0-x86_64-i386-64bit
     optional deps. installed: ['typing-extensions']

This is kinda related to #2135, but a different enough case that it probably warrants its own issue.

In that bug, it was said "pydantic tries to coerce in the order of the union". The docs say something similar: "pydantic will attempt to 'match' any of the types defined under Union and will use the first one that matches."

That behavior appears to not work for bools -- bools seem to be cooerced to ints or floats if int or float is defined in the list:

import typing as t
from pydantic import BaseModel

class UnionTest(BaseModel):
     mixed: t.Optional[ t.Union[bool, int, str] ]

UnionTest(mixed=False)
# ===> UnionTest(mixed=0) -- BUG: coerced into int, not the bool!
@dlopuch dlopuch added the bug V1 Bug related to Pydantic V1.X label Apr 26, 2021
@PrettyWood
Copy link
Member

PrettyWood commented Apr 26, 2021

@dlopuch If you can use python 3.7+ you won't have this issue
This works in 3.6 and fails with 3.7+

from typing import Union

assert Union[bool, int, str] == Union[int, str]

PS: As a workaround for python 3.6, you can use StrictBool

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

No branches or pull requests

2 participants