Skip to content

Commit e5360e4

Browse files
committed
[#241] fixes the issue where defaults from the config path were not being passed when using subparsers (field_wrapper.py). Additionally fixes an issue where subdataclasses were requiring every value to be defaulted in the config path, instead of falling back to the default in the dataclass definition if it wasn't (dataclass_wrapper.py)
1 parent f4dee55 commit e5360e4

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

simple_parsing/wrappers/dataclass_wrapper.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -264,8 +264,15 @@ def defaults(self) -> list[DataclassT | dict[str, Any] | None | Literal[argparse
264264
self._defaults = []
265265
for default in self.parent.defaults:
266266
if default not in (None, argparse.SUPPRESS):
267-
default = getattr(default, self.name)
268-
self._defaults.append(default)
267+
# we need to check here if the default has been provided.
268+
# If not we'll use the default_value option function
269+
if hasattr(default, self.name):
270+
default = getattr(default, self.name)
271+
else:
272+
default = utils.default_value(self._field)
273+
if default is MISSING:
274+
continue
275+
self._defaults.append(default)
269276
else:
270277
default_field_value = utils.default_value(self._field)
271278
if default_field_value is MISSING:

simple_parsing/wrappers/field_wrapper.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -1030,7 +1030,12 @@ def add_subparsers(self, parser: ArgumentParser):
10301030
# Just for typing correctness, as we didn't explicitly change
10311031
# the return type of subparsers.add_parser method.)
10321032
subparser = cast("ArgumentParser", subparser)
1033-
subparser.add_arguments(dataclass_type, dest=self.dest)
1033+
# we need to propagate the defaults down to the sub dataclass if they've been set.
1034+
# there may need to be some error handling here in case the use has specified the wrong values for the default.
1035+
if isinstance(self.default, dict) and self.default.get(subcommand, None) is not None:
1036+
subparser.add_arguments(dataclass_type, dest=self.dest, default=dataclass_type(**self.default[subcommand]))
1037+
else:
1038+
subparser.add_arguments(dataclass_type, dest=self.dest)
10341039

10351040
def equivalent_argparse_code(self):
10361041
arg_options = self.arg_options.copy()

0 commit comments

Comments
 (0)