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
standag committed Oct 3, 2023
1 parent e0b207f commit 3881eb1
Show file tree
Hide file tree
Showing 2 changed files with 25 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
7 changes: 4 additions & 3 deletions typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import click

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 +817,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 3881eb1

Please sign in to comment.