Skip to content

Commit

Permalink
🐛 Fix usage of Annotated with future annotations in Python 3.8
Browse files Browse the repository at this point in the history
Fixes #802

`RuntimeError: Type not yet supported: typing_extensions.Annotated[...]`

The solution is to use the `get_type_hints` method from `typing_extensions`
instead of the built-in in the `typing` module, as it includes backports that
support properly evaluating the forward reference.
  • Loading branch information
ivantodorovich committed Apr 30, 2024
1 parent 8bffffd commit ab857cb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
26 changes: 26 additions & 0 deletions tests/test_future_annotations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from __future__ import annotations

import typer
from typer.testing import CliRunner
from typing_extensions import Annotated

runner = CliRunner()


def test_annotated():
app = typer.Typer()

@app.command()
def cmd(force: Annotated[bool, typer.Option("--force")] = False):
if force:
print("Forcing operation")
else:
print("Not forcing")

result = runner.invoke(app)
assert result.exit_code == 0, result.output
assert "Not forcing" in result.output

result = runner.invoke(app, ["--force"])
assert result.exit_code == 0, result.output
assert "Forcing operation" in result.output
4 changes: 2 additions & 2 deletions typer/utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import inspect
import sys
from copy import copy
from typing import Any, Callable, Dict, List, Tuple, Type, cast, get_type_hints
from typing import Any, Callable, Dict, List, Tuple, Type, cast

from typing_extensions import Annotated
from typing_extensions import Annotated, get_type_hints

from ._typing import get_args, get_origin
from .models import ArgumentInfo, OptionInfo, ParameterInfo, ParamMeta
Expand Down

0 comments on commit ab857cb

Please sign in to comment.