Skip to content

Commit c5e2390

Browse files
authored
New auto_parser function for convenience and more visibility of the capture_parser feature (#721)
1 parent dbc6398 commit c5e2390

File tree

5 files changed

+76
-4
lines changed

5 files changed

+76
-4
lines changed

CHANGELOG.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ paths are considered internals and can change in minor and patch releases.
1515
v4.40.0 (2025-05-??)
1616
--------------------
1717

18+
Added
19+
^^^^^
20+
- New ``auto_parser`` function for convenience and more visibility of the
21+
``capture_parser`` feature (`#721
22+
<https://github.com/omni-us/jsonargparse/pull/721>`__).
23+
1824
Fixed
1925
^^^^^
2026
- ``set_parsing_settings(validate_defaults=True)`` fails when the parser has a

DOCUMENTATION.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,8 @@ This can be easily implemented with :func:`.capture_parser` as follows:
329329
.. note::
330330

331331
The official way to obtain the parser for command line tools based on
332-
:func:`.auto_cli` is by using :func:`.capture_parser`.
332+
:func:`.auto_cli` is by using :func:`.auto_parser`, which is just a
333+
convenience function that calls :func:`.capture_parser`.
333334

334335

335336
Optionals as positionals

README.rst

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,49 @@ a `substantial user base
2727
it serves as the framework behind pytorch-lightning's `LightningCLI
2828
<https://lightning.ai/docs/pytorch/stable/cli/lightning_cli.html>`__.
2929

30+
Teaser examples
31+
---------------
32+
33+
CLI with minimal boilerplate:
34+
35+
.. code-block:: python
36+
37+
from jsonargparse import auto_cli
38+
39+
def main_function(...): # your main parameters and logic here
40+
...
41+
42+
if __name__ == "__main__":
43+
auto_cli(main_function) # parses arguments and runs main_function
44+
45+
Minimal boilerplate but manually parsing:
46+
47+
.. code-block:: python
48+
49+
from jsonargparse import auto_parser
50+
51+
...
52+
53+
if __name__ == "__main__":
54+
parser = auto_parser(main_function)
55+
cfg = parser.parse_args()
56+
...
57+
58+
Powerful argparse-like low level parsers:
59+
60+
.. code-block:: python
61+
62+
from typing import Union, Literal
63+
from jsonargparse import ArgumentParser
64+
65+
parser = ArgumentParser()
66+
parser.add_argument("--config", action="config") # support config files
67+
parser.add_argument("--opt", type=Union[int, Literal["off"]) # complex arguments via type hints
68+
parser.add_function_arguments(main_function, "function") # add entire function signatures
69+
...
70+
cfg = parser.parse_args()
71+
...
72+
3073
3174
Features
3275
--------

jsonargparse/_cli.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,13 @@
88
from ._deprecated import deprecation_warning_cli_return_parser
99
from ._namespace import Namespace, dict_to_namespace
1010
from ._optionals import get_doc_short_description
11-
from ._util import default_config_option_help
11+
from ._util import capture_parser, default_config_option_help
1212

13-
__all__ = ["CLI", "auto_cli"]
13+
__all__ = [
14+
"CLI",
15+
"auto_cli",
16+
"auto_parser",
17+
]
1418

1519

1620
ComponentType = Union[Callable, Type]
@@ -125,6 +129,14 @@ def auto_cli(
125129
return _run_component(component, init.get(subcommand))
126130

127131

132+
def auto_parser(*args, **kwargs) -> ArgumentParser:
133+
"""Same as auto_cli, but returns the parser, so doesn't parse arguments or run.
134+
135+
This is a shorthand for ``capture_parser(lambda: auto_cli(*args, **kwargs))``.
136+
"""
137+
return capture_parser(lambda: auto_cli(*args, **kwargs))
138+
139+
128140
def get_help_str(component, logger):
129141
if isinstance(component, dict):
130142
return component.get("_help")

jsonargparse_tests/test_cli.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515

1616
import pytest
1717

18-
from jsonargparse import CLI, auto_cli, capture_parser, lazy_instance
18+
from jsonargparse import CLI, auto_cli, auto_parser, capture_parser, lazy_instance
19+
from jsonargparse._namespace import Namespace
1920
from jsonargparse._optionals import docstring_parser_support, ruyaml_support
2021
from jsonargparse.typing import final
2122
from jsonargparse_tests.conftest import json_or_yaml_dump, json_or_yaml_load, skip_if_docstring_parser_unavailable
@@ -28,6 +29,15 @@ def get_cli_stdout(*args, **kwargs) -> str:
2829
return out.getvalue()
2930

3031

32+
def simple_main(a1: int = 0, a2: bool = False):
33+
pass
34+
35+
36+
def test_auto_parser():
37+
parser = auto_parser(simple_main)
38+
assert parser.parse_args([]) == Namespace(config=None, a1=0, a2=False)
39+
40+
3141
# failure cases
3242

3343

0 commit comments

Comments
 (0)