From 665786e8c98985db9a9da22548e545defe6e79cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D0=B4=D1=80=D0=B5=D0=B9=20=D0=9A=D0=B0=D0=B7?= =?UTF-8?q?=D0=B0=D0=BD=D1=86=D0=B5=D0=B2?= Date: Tue, 19 Dec 2023 13:04:56 +0400 Subject: [PATCH] Add eval_str to inspect.signature --- tests/test_annotated.py | 19 +++++++++++++++++++ typer/utils.py | 7 ++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/tests/test_annotated.py b/tests/test_annotated.py index 6436ad668e..4d4c0353ce 100644 --- a/tests/test_annotated.py +++ b/tests/test_annotated.py @@ -1,3 +1,5 @@ +import sys +import pytest import typer from typer.testing import CliRunner from typing_extensions import Annotated @@ -21,6 +23,23 @@ def cmd(val: Annotated[int, typer.Argument()] = 0): assert "hello 42" in result.output +@pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python3.10 or higher") +def test_annotated_argument_in_string_type_with_default(): + app = typer.Typer() + + @app.command() + def cmd(val: "Annotated[int, typer.Argument()]" = 0): + print(f"hello {val}") + + result = runner.invoke(app) + assert result.exit_code == 0, result.output + assert "hello 0" in result.output + + result = runner.invoke(app, ["42"]) + assert result.exit_code == 0, result.output + assert "hello 42" in result.output + + def test_annotated_argument_with_default_factory(): app = typer.Typer() diff --git a/typer/utils.py b/typer/utils.py index 44816e2420..2ba7bace45 100644 --- a/typer/utils.py +++ b/typer/utils.py @@ -1,4 +1,5 @@ import inspect +import sys from copy import copy from typing import Any, Callable, Dict, List, Tuple, Type, cast, get_type_hints @@ -106,7 +107,11 @@ def _split_annotation_from_typer_annotations( def get_params_from_function(func: Callable[..., Any]) -> Dict[str, ParamMeta]: - signature = inspect.signature(func) + if sys.version_info >= (3, 10): + signature = inspect.signature(func, eval_str=True) + else: + signature = inspect.signature(func) + type_hints = get_type_hints(func) params = {} for param in signature.parameters.values():