Skip to content

Commit 11a817c

Browse files
authored
Fix default help text for union of submodels. (#472)
1 parent 87ad4db commit 11a817c

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
@@ -1563,6 +1563,15 @@ def _add_parser_args(
15631563
) -> ArgumentParser:
15641564
subparsers: Any = None
15651565
alias_path_args: dict[str, str] = {}
1566+
# Ignore model default if the default is a model and not a subclass of the current model.
1567+
model_default = (
1568+
None
1569+
if (
1570+
(is_model_class(type(model_default)) or is_pydantic_dataclass(type(model_default)))
1571+
and not issubclass(type(model_default), model)
1572+
)
1573+
else model_default
1574+
)
15661575
for field_name, field_info in self._sort_arg_fields(model):
15671576
sub_models: list[type[BaseModel]] = self._get_sub_models(model, field_name, field_info)
15681577
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
@@ -447,6 +447,46 @@ class MultilineDoc(BaseSettings, cli_parse_args=True):
447447
)
448448

449449

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

0 commit comments

Comments
 (0)