Skip to content

Commit

Permalink
improve smart_union
Browse files Browse the repository at this point in the history
  • Loading branch information
PrettyWood committed Sep 5, 2021
1 parent f8c0c56 commit eeaca09
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 14 deletions.
3 changes: 2 additions & 1 deletion pydantic/fields.py
Expand Up @@ -956,7 +956,8 @@ def _validate_singleton(
if isinstance(v, field.outer_type_):
return v, None
except TypeError:
pass
if isinstance(v, get_origin(field.outer_type_)):
return v, None

# 1st pass by default or 3rd pass with `smart_union` enabled:
# check if the value can be coerced into one of the Union types
Expand Down
30 changes: 17 additions & 13 deletions tests/test_types.py
Expand Up @@ -2936,29 +2936,33 @@ class Config:


def test_default_union_compound_types():
class DefaultModel(BaseModel):
class Model(BaseModel):
values: Union[Dict[str, str], List[str]]

assert DefaultModel(values={'L': '1'}).dict() == {'values': {'L': '1'}}
assert DefaultModel(values=['L1']).dict() == {'values': {'L': '1'}} # dict(['L1']) == {'L': '1'}
assert Model(values={'L': '1'}).dict() == {'values': {'L': '1'}}
assert Model(values=['L1']).dict() == {'values': {'L': '1'}} # dict(['L1']) == {'L': '1'}


def test_smart_union_compound_types():
"""For now, `smart_union` does not support well compound types"""

class DefaultModel(BaseModel):
class Model(BaseModel):
values: Union[Dict[str, str], List[str]]

class Config:
smart_union = True

assert DefaultModel(values={'L': '1'}).dict() == {'values': {'L': '1'}}
assert DefaultModel(values=['L1']).dict() == {
'values': {'L': '1'}
} # should be `['L1']` once `smart_union` is improved
assert DefaultModel(values=('L1',)).dict() == {
'values': {'L': '1'}
} # expected! (still coerce as tuple is not a list)
assert Model(values={'L': '1'}).dict() == {'values': {'L': '1'}}
assert Model(values=['L1']).dict() == {'values': ['L1']}
assert Model(values=('L1',)).dict() == {'values': {'L': '1'}} # expected! (still coerce as tuple is not a list)


def test_smart_union_compouned_types_edge_case():
"""For now, `smart_union` does not support well compound types"""

class Model(BaseModel):
x: Union[List[str], List[int]]

# should consider [1, 2] valid and not coerce once `smart_union` is improved
assert Model(x=[1, 2]).x == ['1', '2']


@pytest.mark.parametrize(
Expand Down

0 comments on commit eeaca09

Please sign in to comment.