Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
7 changes: 6 additions & 1 deletion simple_parsing/wrappers/field_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,12 @@ def parse_optional(t: type[T]) -> Callable[[Optional[Any]], Optional[T]]:
parse = get_parsing_fn(t)

def _parse_optional(val: Optional[Any]) -> Optional[T]:
return val if val is None else parse(val)
if val is None:
return val
elif isinstance(val, str) and val == "None":
return None
else:
return parse(val)

return _parse_optional

Expand Down
20 changes: 20 additions & 0 deletions test/test_optional.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,26 @@ def test_optional_seed():
assert config == Config(123)


@dataclass
class Config2:
var_with_default: Optional[int] = 42


def test_optional_with_default_value():
"""Test that a value marked as Optional with a default value can be overridden to None.
"""
parser = ArgumentParser()
parser.add_arguments(Config2, dest="config")

args = parser.parse_args("".split())
config: Config2 = args.config
assert config == Config2(var_with_default=42)

args = parser.parse_args("--var_with_default".split())
config: Config2 = args.config
assert config == Config2(var_with_default=None)


@dataclass
class Child:
name: str = "Kevin"
Expand Down