Skip to content

Commit

Permalink
fix: add support for UnionType annotation
Browse files Browse the repository at this point in the history
  • Loading branch information
standa-kiwi committed Oct 3, 2023
1 parent e0b207f commit 8b29313
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
21 changes: 21 additions & 0 deletions tests/test_type_conversion.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import sys
from enum import Enum
from pathlib import Path
from typing import Any, List, Optional, Tuple
Expand Down Expand Up @@ -128,3 +129,23 @@ def custom_click_type(

result = runner.invoke(app, ["0x56"])
assert result.exit_code == 0


@pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python3.10 or higher")
def test_optional_via_uniontype():
app = typer.Typer()

@app.command()
def opt(user: str | None = None):
if user:
print(f"User: {user}")
else:
print("No user")

result = runner.invoke(app)
assert result.exit_code == 0
assert "No user" in result.output

result = runner.invoke(app, ["--user", "Camila"])
assert result.exit_code == 0
assert "User: Camila" in result.output
8 changes: 5 additions & 3 deletions typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
from uuid import UUID

import click
from typing_extensions import get_origin

from ._typing import get_origin, is_union
from .completion import get_completion_inspect_parameters
from .core import MarkupMode, TyperArgument, TyperCommand, TyperGroup, TyperOption
from .models import (
Expand Down Expand Up @@ -816,10 +818,10 @@ def get_click_param(
is_tuple = False
parameter_type: Any = None
is_flag = None
origin = getattr(main_type, "__origin__", None)
origin = get_origin(main_type)
if origin is not None:
# Handle Optional[SomeType]
if origin is Union:
# Handle `Optional[SomeType]` and `str | None`
if is_union(origin):
types = []
for type_ in main_type.__args__:
if type_ is NoneType:
Expand Down

0 comments on commit 8b29313

Please sign in to comment.