Skip to content

Commit

Permalink
Deduce type from default value
Browse files Browse the repository at this point in the history
  • Loading branch information
jvanvugt committed Sep 21, 2019
1 parent 517788d commit 748fd8c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
9 changes: 7 additions & 2 deletions auto_cli/parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,14 @@ def create_parser(command: Command) -> ArgumentParser:
param_types = command.parameter_types or {}
for param_name, parameter in parameters.items():
annotation = param_types.get(param_name, parameter.annotation)
has_default_value = _has_default(parameter)
if annotation == inspect.Parameter.empty and has_default_value:
# Deduce the type from the default value
annotation = type(parameter.default)

kwargs = {
"required": not _has_default(parameter),
"default": parameter.default if _has_default(parameter) else None,
"required": not has_default_value,
"default": parameter.default if has_default_value else None,
# The params above might be overwritten by the function below
**_get_type_params(annotation, param_name, function),
}
Expand Down
9 changes: 9 additions & 0 deletions auto_cli/tests/test_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ def func_to_test(a: Tuple[int, int], b: bool) -> int:
assert args == {"a": nums, "b": False}


def test_type_from_default() -> None:
def func_to_test(a=4) -> int:
return a

parser = create_parser(Command.from_func(func_to_test))
args = parser.parse(["--a", "4"])
assert args == {"a": 4}


def test_override_param_type() -> None:
def func_to_test(a: int, b):
return a + b
Expand Down

0 comments on commit 748fd8c

Please sign in to comment.