Skip to content

Commit 0a9faca

Browse files
authored
Fix command line help from argparse formatting problem (#307)
1 parent 813ac94 commit 0a9faca

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

pydantic_settings/sources.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1407,7 +1407,7 @@ def _help_format(self, field_info: FieldInfo) -> str:
14071407
elif field_info.default_factory is not None:
14081408
default = f'(default: {field_info.default_factory})'
14091409
_help += f' {default}' if _help else default
1410-
return _help
1410+
return _help.replace('%', '%%') if issubclass(type(self._root_parser), ArgumentParser) else _help
14111411

14121412

14131413
class ConfigFileSourceMixin(ABC):

tests/test_settings.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2261,6 +2261,29 @@ class Cfg(BaseSettings):
22612261
)
22622262

22632263

2264+
def test_cli_help_string_format(capsys, monkeypatch):
2265+
class Cfg(BaseSettings):
2266+
date_str: str = '%Y-%m-%d'
2267+
2268+
argparse_options_text = 'options' if sys.version_info >= (3, 10) else 'optional arguments'
2269+
2270+
with monkeypatch.context() as m:
2271+
m.setattr(sys, 'argv', ['example.py', '--help'])
2272+
2273+
with pytest.raises(SystemExit):
2274+
Cfg(_cli_parse_args=True)
2275+
2276+
assert (
2277+
re.sub(r'0x\w+', '0xffffffff', capsys.readouterr().out, re.MULTILINE)
2278+
== f"""usage: example.py [-h] [--date_str str]
2279+
2280+
{argparse_options_text}:
2281+
-h, --help show this help message and exit
2282+
--date_str str (default: %Y-%m-%d)
2283+
"""
2284+
)
2285+
2286+
22642287
def test_cli_nested_dataclass_arg():
22652288
@pydantic_dataclasses.dataclass
22662289
class MyDataclass:

0 commit comments

Comments
 (0)