Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use properties of class component as subcommands. #1

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
33 changes: 28 additions & 5 deletions jsonargparse/_cli.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
"""Simple creation of command line interfaces."""

import inspect
from typing import Any, Callable, Dict, List, Optional, Type, Union
from typing import Any, Callable, Dict, List, Optional, Type, Union, get_type_hints

from ._actions import ActionConfigFile, _ActionPrintConfig, remove_actions
from ._core import ArgumentParser
from ._deprecated import deprecation_warning_cli_return_parser
from ._namespace import Namespace, dict_to_namespace
from ._optionals import get_doc_short_description
from ._parameter_resolvers import is_property
from ._util import default_config_option_help

__all__ = ["CLI"]
Expand Down Expand Up @@ -148,16 +149,17 @@ def _add_subcommands(
remove_actions(subparser, (ActionConfigFile, _ActionPrintConfig))


def _add_component_to_parser(component, parser, as_positional, fail_untyped, config_help):
def _add_component_to_parser(component, parser, as_positional, fail_untyped, config_help, ignore_class_args=False):
kwargs = dict(as_positional=as_positional, fail_untyped=fail_untyped, sub_configs=True)
if inspect.isclass(component):
subcommand_keys = [k for k, v in inspect.getmembers(component) if callable(v) and k[0] != "_"]
if not subcommand_keys:
subcomponent_keys = [k for k, v in inspect.getmembers(component) if is_property(v) and k[0] != "_"]
if not subcommand_keys and not subcomponent_keys:
added_args = parser.add_class_arguments(component, as_group=False, **kwargs)
if not parser.description:
parser.description = get_help_str(component, parser.logger)
return added_args
added_args = parser.add_class_arguments(component, **kwargs)
added_args = parser.add_class_arguments(component, **kwargs) if not ignore_class_args else []
subcommands = parser.add_subcommands(required=True)
for key in subcommand_keys:
description = get_help_str(getattr(component, key), parser.logger)
Expand All @@ -168,6 +170,18 @@ def _add_component_to_parser(component, parser, as_positional, fail_untyped, con
if not added_subargs:
remove_actions(subparser, (ActionConfigFile, _ActionPrintConfig))
subcommands.add_subcommand(key, subparser, help=get_help_str(getattr(component, key), parser.logger))
for key in subcomponent_keys:
subcomponent = get_type_hints(getattr(component, key).fget)["return"]
description = get_doc_short_description(getattr(component, key), logger=parser.logger)
if not description:
description = get_help_str(subcomponent, logger=parser.logger)
subparser = type(parser)(description=description)
subparser.add_argument("--config", action=ActionConfigFile, help=config_help)
subcommands.add_subcommand(key, subparser, help=description)
added_subargs = _add_component_to_parser(
subcomponent, subparser, as_positional, fail_untyped, config_help, ignore_class_args=True
)
added_args += [f"{key}.{a}" for a in added_subargs]
else:
added_args = parser.add_function_arguments(component, as_group=False, **kwargs)
if not parser.description:
Expand All @@ -185,4 +199,13 @@ def _run_component(component, cfg):
subcommand_cfg = cfg.pop(subcommand, {})
subcommand_cfg.pop("config", None)
component_obj = component(**cfg)
return getattr(component_obj, subcommand)(**subcommand_cfg)
component_obj = getattr(component_obj, subcommand)
while "subcommand" in subcommand_cfg:
subcommand = subcommand_cfg.pop("subcommand")
subcommand_cfg = subcommand_cfg.pop(subcommand, {})
subcommand_cfg.pop("config", None)
component_obj = getattr(component_obj, subcommand)
if not callable(component_obj):
assert not subcommand_cfg
return component_obj
return component_obj(**subcommand_cfg)
137 changes: 137 additions & 0 deletions jsonargparse_tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,143 @@ def test_single_class_print_config_before_subcommand():
assert cfg == {"i1": "0", "method1": {"m1": 2}}


# multi-layered class tests


class Layer3:
"""Description of Layer3."""

def __init__(self, i3: str):
self.i3 = i3

def method3(self, m3: int):
"""Description of method3"""
return "method3", self.i3, m3


class Layer2:
"""Description of Layer2."""

def __init__(self, i2: str):
self.i2 = i2

def method2(self, m2: int):
"""Description of method2"""
return "method2", self.i2, m2

@property
def layer3(self) -> Layer3:
return Layer3(self.i2)


class Layer1:
def __init__(self, i1: str = "d"):
self.i1 = i1

def method1(self, m1: int):
"""Description of method1"""
return "method1", self.i1, m1

@property
def layer2(self) -> Layer2:
return Layer2(self.i1)


@pytest.mark.parametrize(
["expected", "args"],
[
(("method1", "0", 1), ["--i1=0", "method1", "1"]),
(("method2", "0", 1), ["--i1=0", "layer2", "method2", "1"]),
(("method3", "0", 1), ["--i1=0", "layer2", "layer3", "method3", "1"]),
(("method1", "d", 1), ["method1", "1"]),
(("method2", "d", 1), ["layer2", "method2", "1"]),
(("method3", "d", 1), ["layer2", "layer3", "method3", "1"]),
(("method1", "0", 1), ['--config={"i1": "0", "method1": {"m1": 1}}']),
(("method2", "0", 1), ['--config={"i1": "0", "layer2": {"method2": {"m2": 1}}}']),
(("method3", "0", 1), ['--config={"i1": "0", "layer2": {"layer3": {"method3": {"m3": 1}}}}']),
(("method1", "d", 1), ['--config={"method1": {"m1": 1}}']),
(("method2", "d", 1), ['--config={"layer2": {"method2": {"m2": 1}}}']),
(("method3", "d", 1), ['--config={"layer2": {"layer3": {"method3": {"m3": 1}}}}']),
(("method1", "d", 1), ["method1", '--config={"m1": 1}']),
(("method2", "d", 1), ["layer2", '--config={"method2": {"m2": 1}}']),
(("method3", "d", 1), ["layer2", "layer3", '--config={"method3": {"m3": 1}}']),
],
)
def test_multi_layered_class_return(expected, args):
assert expected == CLI(Layer1, args=args)


@pytest.mark.parametrize(
["expected", "args"],
[
("{method1,layer2}", ["--help"]),
("{method2,layer3}", ["layer2", "--help"]),
("{method3}", ["layer2", "layer3", "--help"]),
],
)
def test_multi_layered_class_subcommand_help(expected, args):
out = get_cli_stdout(Layer1, args=args)
assert expected in out


@pytest.mark.parametrize(
["expected_choices", "expected_subcommands", "args"],
[
("{method1,layer2}", ("method1", "Layer2"), ["--help"]),
("{method2,layer3}", ("method2", "Layer3"), ["layer2", "--help"]),
("{method3}", ("method3",), ["layer2", "layer3", "--help"]),
],
)
def test_multi_layered_class_help(expected_choices, expected_subcommands, args):
out = get_cli_stdout(Layer1, args=args)
assert expected_choices in out
if docstring_parser_support:
for name in expected_subcommands:
assert f"Description of {name}" in out


class EmptyLayer:
"""Docstring of EmptyLayer."""


class TopLayerWithEmptyLayer:
@property
def empty(self) -> EmptyLayer:
return EmptyLayer()


class TopLayerWithDocstring:
@property
def with_doc(self) -> EmptyLayer:
"""Docstring of with_doc."""
return EmptyLayer()

@property
def without_doc(self) -> EmptyLayer:
return EmptyLayer()


def test_multi_layered_class_property_help():
out = get_cli_stdout(TopLayerWithDocstring, args=["--help"])
assert "with_doc Docstring of with_doc." in out
assert "without_doc Docstring of EmptyLayer." in out


def test_multi_layered_class_without_methods():
expected = CLI(EmptyLayer, args=[])
actual = CLI(TopLayerWithEmptyLayer, args=["empty"])
assert type(actual) is type(expected)


def test_multi_layered_class_without_methods_help():
expected = get_cli_stdout(EmptyLayer, args=["--help"])
actual = get_cli_stdout(TopLayerWithEmptyLayer, args=["empty", "--help"])
# Omit usage line.
expected = expected.split("\n\n", maxsplit=1)[1]
actual = actual.split("\n\n", maxsplit=1)[1]
assert actual == expected


# function and class tests


Expand Down