From 748fd8c5681525deab969e145de65cb673352231 Mon Sep 17 00:00:00 2001 From: Joris van Vugt Date: Sat, 21 Sep 2019 21:01:23 +0200 Subject: [PATCH] Deduce type from default value --- auto_cli/parsing.py | 9 +++++++-- auto_cli/tests/test_parsing.py | 9 +++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/auto_cli/parsing.py b/auto_cli/parsing.py index 6cf76f1..2118542 100644 --- a/auto_cli/parsing.py +++ b/auto_cli/parsing.py @@ -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), } diff --git a/auto_cli/tests/test_parsing.py b/auto_cli/tests/test_parsing.py index 47a173c..c24aa02 100644 --- a/auto_cli/tests/test_parsing.py +++ b/auto_cli/tests/test_parsing.py @@ -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