Skip to content

Commit

Permalink
Fix double nested dataclass defaults, bump version
Browse files Browse the repository at this point in the history
  • Loading branch information
brentyi committed Oct 23, 2021
1 parent e1e1fb3 commit e58e0d8
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
10 changes: 7 additions & 3 deletions dcargs/_parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,18 @@ def from_dataclass(

# Add arguments for nested dataclasses.
if _resolver.is_dataclass(field.type):
default = None
if default_instance is not None:
default = getattr(default_instance, field.name)
elif field.default is not dataclasses.MISSING:
default = field.default

child_definition, child_metadata = ParserDefinition.from_dataclass(
field.type,
parent_dataclasses | {cls},
subparser_name_from_type=subparser_name_from_type,
parent_type_from_typevar=type_from_typevar,
default_instance=field.default
if field.default is not dataclasses.MISSING
else None,
default_instance=default,
)
metadata.update(child_metadata)

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name="dcargs",
version="0.0.4",
version="0.0.5",
description="Portable, reusable, strongly typed CLIs from dataclass definitions",
long_description=long_description,
long_description_content_type="text/markdown",
Expand Down
22 changes: 22 additions & 0 deletions tests/test_nested.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,28 @@ class Nested:
assert dcargs.parse(Nested, args=["--x", "1"]) == Nested(x=1, b=B(y=5))


def test_double_default_nested():
@dataclasses.dataclass
class Child:
y: int

@dataclasses.dataclass
class Parent:
c: Child

@dataclasses.dataclass
class Grandparent:
x: int
b: Parent = Parent(Child(y=5))

assert dcargs.parse(Grandparent, args=["--x", "1", "--b.c.y", "3"]) == Grandparent(
x=1, b=Parent(Child(y=3))
)
assert dcargs.parse(Grandparent, args=["--x", "1"]) == Grandparent(
x=1, b=Parent(Child(y=5))
)


# TODO: implement this!
# def test_optional_nested():
# @dataclasses.dataclass
Expand Down

0 comments on commit e58e0d8

Please sign in to comment.