File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff 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 (
Original file line number Diff line number Diff 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+
451491def test_cli_help_default_or_none_model (capsys , monkeypatch ):
452492 class DeeperSubModel (BaseModel ):
453493 flag : bool
You can’t perform that action at this time.
0 commit comments