Skip to content

Commit

Permalink
Fix command line help from argparse formatting problem (#307)
Browse files Browse the repository at this point in the history
  • Loading branch information
scottstanie authored Jun 10, 2024
1 parent 813ac94 commit 0a9faca
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pydantic_settings/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -1407,7 +1407,7 @@ def _help_format(self, field_info: FieldInfo) -> str:
elif field_info.default_factory is not None:
default = f'(default: {field_info.default_factory})'
_help += f' {default}' if _help else default
return _help
return _help.replace('%', '%%') if issubclass(type(self._root_parser), ArgumentParser) else _help


class ConfigFileSourceMixin(ABC):
Expand Down
23 changes: 23 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -2261,6 +2261,29 @@ class Cfg(BaseSettings):
)


def test_cli_help_string_format(capsys, monkeypatch):
class Cfg(BaseSettings):
date_str: str = '%Y-%m-%d'

argparse_options_text = 'options' if sys.version_info >= (3, 10) else 'optional arguments'

with monkeypatch.context() as m:
m.setattr(sys, 'argv', ['example.py', '--help'])

with pytest.raises(SystemExit):
Cfg(_cli_parse_args=True)

assert (
re.sub(r'0x\w+', '0xffffffff', capsys.readouterr().out, re.MULTILINE)
== f"""usage: example.py [-h] [--date_str str]
{argparse_options_text}:
-h, --help show this help message and exit
--date_str str (default: %Y-%m-%d)
"""
)


def test_cli_nested_dataclass_arg():
@pydantic_dataclasses.dataclass
class MyDataclass:
Expand Down

0 comments on commit 0a9faca

Please sign in to comment.