Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for optional as UnionType (Python >= 3.10) #739

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -29,6 +30,26 @@ def opt(user: Optional[str] = None):
assert "User: Camila" in result.output


@pytest.mark.skipif(sys.version_info < (3, 10), reason="requires python3.10 or higher")
def test_optional_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


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

Expand Down
20 changes: 19 additions & 1 deletion typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@
except ImportError: # pragma: nocover
rich = None # type: ignore

if sys.version_info >= (3, 10):
from types import UnionType
else:
# Python < 3.10 doesn't have UnionType, so we define it manually as non inheritable type
UnionType = type("", (), {})

_original_except_hook = sys.excepthook
_typer_developer_exception_attr_name = "__typer_developer_exception__"

Expand Down Expand Up @@ -816,8 +822,9 @@ def get_click_param(
is_tuple = False
parameter_type: Any = None
is_flag = None
is_union_type = lenient_issubclass(type(main_type), UnionType)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, I'm new to this kind of stuff, could you please clarify this for me please? From the variable name, it is a type already, why do we need to convert it to type() here? Is it just your preference or there are some edge cases being handled implicitly here?

origin = getattr(main_type, "__origin__", None)
if origin is not None:
if origin is not None or is_union_type:
# Handle Optional[SomeType]
if origin is Union:
types = []
Expand All @@ -828,6 +835,17 @@ def get_click_param(
assert len(types) == 1, "Typer Currently doesn't support Union types"
main_type = types[0]
origin = getattr(main_type, "__origin__", None)
# Handle (SomeType | None)
elif is_union_type:
types = []
for type_ in main_type.__args__:
if type_ is NoneType:
continue
types.append(type_)
assert (
len(types) == 1
), "Typer Currently doesn't support UnionType other than (T | None)"
main_type = types[0]
# Handle Tuples and Lists
if lenient_issubclass(origin, List):
main_type = main_type.__args__[0]
Expand Down
Loading