Skip to content

Commit 31e18d9

Browse files
committed
Merge branch 'main' into cli-mutually-exclusive-group
2 parents cff7488 + 11a817c commit 31e18d9

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

pydantic_settings/sources.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1587,6 +1587,15 @@ def _add_parser_args(
15871587
) -> ArgumentParser:
15881588
subparsers: Any = None
15891589
alias_path_args: dict[str, str] = {}
1590+
# Ignore model default if the default is a model and not a subclass of the current model.
1591+
model_default = (
1592+
None
1593+
if (
1594+
(is_model_class(type(model_default)) or is_pydantic_dataclass(type(model_default)))
1595+
and not issubclass(type(model_default), model)
1596+
)
1597+
else model_default
1598+
)
15901599
for field_name, field_info in self._sort_arg_fields(model):
15911600
sub_models: list[type[BaseModel]] = self._get_sub_models(model, field_name, field_info)
15921601
alias_names, is_alias_path_only = _get_alias_names(

tests/test_source_cli.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,46 @@ class MultilineDoc(BaseSettings, cli_parse_args=True):
448448
)
449449

450450

451+
def test_cli_help_union_of_models(capsys, monkeypatch):
452+
class Cat(BaseModel):
453+
meow: str = 'meow'
454+
455+
class Dog(BaseModel):
456+
bark: str = 'bark'
457+
458+
class Bird(BaseModel):
459+
caww: str = 'caww'
460+
tweet: str
461+
462+
class Tiger(Cat):
463+
roar: str = 'roar'
464+
465+
class Car(BaseSettings, cli_parse_args=True):
466+
driver: Union[Cat, Dog, Bird] = Tiger(meow='purr')
467+
468+
with monkeypatch.context() as m:
469+
m.setattr(sys, 'argv', ['example.py', '--help'])
470+
471+
with pytest.raises(SystemExit):
472+
Car()
473+
assert (
474+
capsys.readouterr().out
475+
== f"""usage: example.py [-h] [--driver JSON] [--driver.meow str] [--driver.bark str]
476+
[--driver.caww str] [--driver.tweet str]
477+
478+
{ARGPARSE_OPTIONS_TEXT}:
479+
-h, --help show this help message and exit
480+
481+
driver options:
482+
--driver JSON set driver from JSON string
483+
--driver.meow str (default: purr)
484+
--driver.bark str (default: bark)
485+
--driver.caww str (default: caww)
486+
--driver.tweet str (ifdef: required)
487+
"""
488+
)
489+
490+
451491
def test_cli_help_default_or_none_model(capsys, monkeypatch):
452492
class DeeperSubModel(BaseModel):
453493
flag: bool

0 commit comments

Comments
 (0)