Skip to content

Commit a903697

Browse files
authored
Strip annotated when getting submodels during CLI parsing. (#490)
1 parent a0924bc commit a903697

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

pydantic_settings/sources.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1434,8 +1434,8 @@ def _get_sub_models(self, model: type[BaseModel], field_name: str, field_info: F
14341434
raise SettingsError(f'CliSubCommand is not outermost annotation for {model.__name__}.{field_name}')
14351435
elif _annotation_contains_types(type_, (_CliPositionalArg,), is_include_origin=False):
14361436
raise SettingsError(f'CliPositionalArg is not outermost annotation for {model.__name__}.{field_name}')
1437-
if is_model_class(type_) or is_pydantic_dataclass(type_):
1438-
sub_models.append(type_) # type: ignore
1437+
if is_model_class(_strip_annotated(type_)) or is_pydantic_dataclass(_strip_annotated(type_)):
1438+
sub_models.append(_strip_annotated(type_))
14391439
return sub_models
14401440

14411441
def _verify_cli_flag_annotations(self, model: type[BaseModel], field_name: str, field_info: FieldInfo) -> None:

tests/test_source_cli.py

+24
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515
BaseModel,
1616
ConfigDict,
1717
DirectoryPath,
18+
Discriminator,
1819
Field,
20+
Tag,
1921
ValidationError,
2022
)
2123
from pydantic import (
@@ -2268,3 +2270,25 @@ class MySettings(BaseSettings):
22682270
CliApp.run(
22692271
MySettings, cli_args=['--bac', 'cli abbrev are invalid for internal parser'], cli_exit_on_error=False
22702272
)
2273+
2274+
2275+
def test_cli_submodels_strip_annotated():
2276+
class PolyA(BaseModel):
2277+
a: int = 1
2278+
type: Literal['a'] = 'a'
2279+
2280+
class PolyB(BaseModel):
2281+
b: str = '2'
2282+
type: Literal['b'] = 'b'
2283+
2284+
def _get_type(model: Union[BaseModel, Dict]) -> str:
2285+
if isinstance(model, dict):
2286+
return model.get('type', 'a')
2287+
return model.type # type: ignore
2288+
2289+
Poly = Annotated[Union[Annotated[PolyA, Tag('a')], Annotated[PolyB, Tag('b')]], Discriminator(_get_type)]
2290+
2291+
class WithUnion(BaseSettings):
2292+
poly: Poly
2293+
2294+
assert CliApp.run(WithUnion, ['--poly.type=a']).model_dump() == {'poly': {'a': 1, 'type': 'a'}}

0 commit comments

Comments
 (0)