Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ Added
choices for unions that also accept open values now require a prefix to be
completed, and literal booleans/``None`` now complete as ``false``/``true``
and ``null`` (`#851 <https://github.com/omni-us/jsonargparse/pull/851>`__).
- ``auto_cli`` now supports a ``return_instance`` parameter to instantiate class
components directly instead of exposing methods as subcommands (`#855
<https://github.com/omni-us/jsonargparse/pull/855>`__).

Fixed
^^^^^
Expand Down
4 changes: 4 additions & 0 deletions DOCUMENTATION.rst
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ Then in a shell you could run:
Note the use of ``as_positional=False`` to make required arguments
non-positional.

To force class instantiation even when the class has public methods, use
``return_instance=True``. This makes :func:`.auto_cli` parse only the class init
arguments and return the class instance, without adding method subcommands.

If more than one function is given to :func:`.auto_cli`, then any of them can be
run via :ref:`sub-commands` similar to the single class example above, i.e.
``example.py function [arguments]`` where ``function`` is the name of the
Expand Down
17 changes: 12 additions & 5 deletions jsonargparse/_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def auto_cli(
config_help: str = default_config_option_help,
set_defaults: Optional[dict[str, Any]] = None,
as_positional: bool = True,
return_instance: bool = False,
fail_untyped: bool = True,
parser_class: type[ArgumentParser] = ArgumentParser,
**kwargs,
Expand All @@ -53,6 +54,8 @@ def auto_cli(
config_help: Help string for config file option in help.
set_defaults: Dictionary of values to override components defaults.
as_positional: Whether to add required parameters as positional arguments.
return_instance: Whether class components should be instantiated directly and returned,
i.e. without exposing class methods as subcommands.
fail_untyped: Whether to raise exception if a required parameter does not have a type.
parser_class: The :class:`ArgumentParser` subclass to use.
**kwargs: Used to instantiate :class:`.ArgumentParser`.
Expand Down Expand Up @@ -95,7 +98,7 @@ def auto_cli(
parser.add_argument("--config", action=ActionConfigFile, help=config_help)

if not isinstance(components, (list, dict)):
_add_component_to_parser(components, parser, as_positional, fail_untyped, config_help)
_add_component_to_parser(components, parser, as_positional, return_instance, fail_untyped, config_help)
if set_defaults is not None:
parser.set_defaults(set_defaults)
if return_parser:
Expand All @@ -108,7 +111,7 @@ def auto_cli(
elif isinstance(components, list):
components = {c.__name__: c for c in components}

_add_subcommands(components, parser, config_help, as_positional, fail_untyped)
_add_subcommands(components, parser, config_help, as_positional, return_instance, fail_untyped)

if set_defaults is not None:
parser.set_defaults(set_defaults)
Expand Down Expand Up @@ -151,6 +154,7 @@ def _add_subcommands(
parser: ArgumentParser,
config_help: str,
as_positional: bool,
return_instance: bool,
fail_untyped: bool,
) -> None:
subcommands = parser.add_subcommands(required=True)
Expand All @@ -162,9 +166,11 @@ def _add_subcommands(
subparser.add_argument("--config", action=ActionConfigFile, help=config_help)
subcommands.add_subcommand(name, subparser, help=description)
if isinstance(component, dict):
_add_subcommands(component, subparser, config_help, as_positional, fail_untyped)
_add_subcommands(component, subparser, config_help, as_positional, return_instance, fail_untyped)
else:
added_args = _add_component_to_parser(component, subparser, as_positional, fail_untyped, config_help)
added_args = _add_component_to_parser(
component, subparser, as_positional, return_instance, fail_untyped, config_help
)
if not added_args:
remove_actions(subparser, (ActionConfigFile, _ActionPrintConfig))

Expand All @@ -177,6 +183,7 @@ def _add_component_to_parser(
component,
parser: ArgumentParser,
as_positional: bool,
return_instance: bool,
fail_untyped: bool,
config_help: str,
):
Expand All @@ -185,7 +192,7 @@ def _add_component_to_parser(
class_methods = [
k for k, v in inspect.getmembers(component) if (callable(v) or isinstance(v, property)) and k[0] != "_"
]
if not class_methods:
if return_instance or not class_methods:
added_args = parser.add_class_arguments(component, as_group=False, **kwargs)
if not parser.description:
parser.description = get_help_str(component, parser.logger)
Expand Down
22 changes: 22 additions & 0 deletions jsonargparse_tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,15 @@ def test_single_class_return():
assert ("5", 6) == auto_cli(Class1, args=["5", "method1", '--config={"m1": 6}'])


def test_single_class_return_instance():
result = auto_cli(Class1, return_instance=True, args=["0"])
assert isinstance(result, Class1)
assert result.i1 == "0"
result = auto_cli(Class1, return_instance=True, args=['--config={"i1": "3"}'])
assert isinstance(result, Class1)
assert result.i1 == "3"


def test_single_class_missing_required_init():
err = StringIO()
with redirect_stderr(err), pytest.raises(SystemExit):
Expand Down Expand Up @@ -215,6 +224,12 @@ def test_single_class_subcommand_help():
assert "Description of method1" in out


def test_single_class_main_help_return_instance():
out = get_cli_stdout(Class1, args=["--help"], return_instance=True)
assert " i1" in out
assert "method1" not in out


@skip_if_docstring_parser_unavailable
def test_single_class_help_docstring_parse_error():
with patch("docstring_parser.parse") as docstring_parse:
Expand Down Expand Up @@ -527,6 +542,13 @@ def test_named_components_deep():
assert ("w", 9) == auto_cli(components, args=["lv1_b", "lv2_z", "lv3_q", "--i1=w", "method1", "--m1=9"], **kw)


def test_named_components_deep_return_instance():
components = {"lv1_b": {"lv2_z": {"lv3_q": Class1}}}
result = auto_cli(components, args=["lv1_b", "lv2_z", "lv3_q", "--i1=w"], as_positional=False, return_instance=True)
assert isinstance(result, Class1)
assert result.i1 == "w"


# config file tests


Expand Down
Loading