Skip to content

Commit

Permalink
Merge pull request #151 from DanCardin/dc/parser-dont-store-has-value…
Browse files Browse the repository at this point in the history
…-false

fix: Avoid storing has_value=False values in the parser.
  • Loading branch information
DanCardin authored Oct 1, 2024
2 parents 49cd483 + e8ad080 commit 78d0580
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
3 changes: 3 additions & 0 deletions docs/source/arg.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,4 +406,7 @@ Principally, `Annotated[SubObject | None, Arg.destructured()]` **could** make se
child options are therefore optional, or that if any child attributes are missing, then that implies
`sub_object=None` at the top level. However both of these are mechanically much more complex than the
feature, as it exists today.

Additionally, this feature only works with the native backend. This **probably** has a workable
solution for argparse, so file an issue if this affects you!
```
4 changes: 3 additions & 1 deletion src/cappa/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,9 @@ def consume_arg(
fulfilled_deps[RawOption] = option

kwargs = fulfill_deps(action_handler, fulfilled_deps)
context.result[field_name] = action_handler(**kwargs)
result = action_handler(**kwargs)
if arg.has_value:
context.result[field_name] = result

check_deprecated(context, arg, option)

Expand Down
24 changes: 24 additions & 0 deletions tests/arg/test_destructured.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,27 @@ def test_destructured_optional():
str(e.value)
== "Destructured arguments currently only support singular concrete types."
)


@dataclass
class CollisionSub:
field1: str = ""
field2: Annotated[str, cappa.Arg(long=True)] = ""


@dataclass
class Collision:
sub: Annotated[CollisionSub, cappa.Arg.destructure()]
field1: int = 0
field2: int = 0


def test_destructured_collision():
result = parse(Collision, "1")
assert result == Collision(sub=CollisionSub("1", ""), field1=0)

result = parse(Collision, "1", "2")
assert result == Collision(sub=CollisionSub("1", ""), field1=2)

result = parse(Collision, "--field2=-1", "1", "2", "3")
assert result == Collision(sub=CollisionSub("1", "-1"), field1=2, field2=3)

0 comments on commit 78d0580

Please sign in to comment.