Skip to content

Commit

Permalink
Backport subparser fix from #5; add test from #9
Browse files Browse the repository at this point in the history
  • Loading branch information
brentyi committed Sep 2, 2022
1 parent 7924ff9 commit 767e4df
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
14 changes: 12 additions & 2 deletions dcargs/_parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,8 @@ def from_field(
# Add subparser for each option.
parser_from_name: Dict[str, ParserSpecification] = {}
for option in options_no_none:
subparser_name = _strings.subparser_name_from_type(prefix, option)
parser_from_name[subparser_name] = ParserSpecification.from_callable(
name = _strings.subparser_name_from_type(prefix, option)
subparser = ParserSpecification.from_callable(
option,
description=None,
parent_classes=parent_classes,
Expand All @@ -268,6 +268,16 @@ def from_field(
avoid_subparsers=avoid_subparsers,
)

# Apply prefix to helptext in nested classes in subparsers.
subparser = dataclasses.replace(
subparser,
helptext_from_nested_class_field_name={
_strings.make_field_name([prefix, k]): v
for k, v in subparser.helptext_from_nested_class_field_name.items()
},
)
parser_from_name[name] = subparser

# Optional if: type hint is Optional[], or a default instance is provided.
required = True
if field.default not in _fields.MISSING_SINGLETONS:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "dcargs"
version = "0.2.7"
version = "0.2.8"
description = "Strongly typed, zero-effort CLI interfaces"
authors = ["brentyi <[email protected]>"]
include = ["./dcargs/**/*"]
Expand Down
27 changes: 27 additions & 0 deletions tests/test_nested.py
Original file line number Diff line number Diff line change
Expand Up @@ -745,3 +745,30 @@ def main(
assert hash(dcargs.cli(main, args="--x.num-epochs 10".split(" "))) == hash(
frozendict({"num_epochs": 10, "batch_size": 64})
)


def test_nested_in_subparser():
# https://github.com/brentyi/dcargs/issues/9
@dataclasses.dataclass(frozen=True)
class Subtype:
data: int = 1

@dataclasses.dataclass(frozen=True)
class TypeA:
subtype: Subtype = Subtype(1)

@dataclasses.dataclass(frozen=True)
class TypeB:
subtype: Subtype = Subtype(2)

@dataclasses.dataclass(frozen=True)
class Wrapper:
supertype: Union[TypeA, TypeB] = TypeA()

assert dcargs.cli(Wrapper, args=[]) == Wrapper()
assert (
dcargs.cli(
Wrapper, args="supertype:type-a --supertype.subtype.data 1".split(" ")
)
== Wrapper()
)

0 comments on commit 767e4df

Please sign in to comment.