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

🐛 Fix support for UnionType with Python 3.11 #676

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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 @@ -147,3 +148,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 @@ -825,10 +826,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
Loading