Skip to content

Commit

Permalink
Add eval_str to inspect.signature
Browse files Browse the repository at this point in the history
  • Loading branch information
heckad committed Dec 19, 2023
1 parent 3a7264c commit f133a9e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
20 changes: 20 additions & 0 deletions tests/test_annotated.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import sys

import pytest
import typer
from typer.testing import CliRunner
from typing_extensions import Annotated
Expand All @@ -21,6 +24,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()

Expand Down
7 changes: 6 additions & 1 deletion typer/utils.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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():
Expand Down

0 comments on commit f133a9e

Please sign in to comment.