Skip to content
Myr

🐛 Fix support for `UnionType` (e.g. `str | None`) with Python 3.11 (#548)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Jonas L. B. · committed by GitHub · parent ad421bd · Browse files · 2 files+37 added−13 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: svlandeg <svlandeg@github.com>
  • Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>

Diff stats

2 files+37 added−13 removed

  • tests:+22 added−0 removed
  • other:+15 added−13 removed

2 files+37 added−13 removed

modified:tests/test_type_conversion.py+22 added
5 unmodified lines
6import pytest7import typer8from typer.testing import CliRunner910from .utils import needs_py3101112runner = CliRunner()131415def test_optional():
14 unmodified lines
30 assert result.exit_code == 031 assert "User: Camila" in result.output323334@needs_py31035def test_union_type_optional():36 app = typer.Typer()3738 @app.command()39 def opt(user: str | None = None):40 if user:41 print(f"User: {user}")42 else:43 print("No user")4445 result = runner.invoke(app)46 assert result.exit_code == 047 assert "No user" in result.output4849 result = runner.invoke(app, ["--user", "Camila"])50 assert result.exit_code == 051 assert "User: Camila" in result.output525354def test_optional_tuple():55 app = typer.Typer()5657 @app.command()
114 unmodified lines
modified:typer/main.py+15 added-13 removed
11 unmodified lines
12from uuid import UUID1314import click1516from ._typing import get_args, get_origin, is_union17from .completion import get_completion_inspect_parameters18from .core import MarkupMode, TyperArgument, TyperCommand, TyperGroup, TyperOption19from .models import (20 AnyType,
804 unmodified lines
825 is_list = False826 is_tuple = False827 parameter_type: Any = None828 is_flag = None828 origin = getattr(main_type, "__origin__", None)829 origin = get_origin(main_type)830831 if origin is not None:830 # Handle Optional[SomeType]831 if origin is Union:832 # Handle SomeType | None and Optional[SomeType]833 if is_union(origin):834 types = []833 for type_ in main_type.__args__:835 for type_ in get_args(main_type):836 if type_ is NoneType:837 continue838 types.append(type_)839 assert len(types) == 1, "Typer Currently doesn't support Union types"840 main_type = types[0]839 origin = getattr(main_type, "__origin__", None)841 origin = get_origin(main_type)842 # Handle Tuples and Lists843 if lenient_issubclass(origin, List):842 main_type = main_type.__args__[0]843 assert not getattr(844 main_type, "__origin__", None844 main_type = get_args(main_type)[0]845 assert not get_origin(846 main_type847 ), "List types with complex sub-types are not currently supported"848 is_list = True849 elif lenient_issubclass(origin, Tuple): # type: ignore850 types = []849 for type_ in main_type.__args__:850 assert not getattr(851 type_, "__origin__", None851 for type_ in get_args(main_type):852 assert not get_origin(853 type_854 ), "Tuple types with complex sub-types are not currently supported"855 types.append(856 get_click_type(annotation=type_, parameter_info=parameter_info)857 )
8 unmodified lines
866 convertor = generate_list_convertor(867 convertor=convertor, default_value=default_value868 )869 if is_tuple:868 convertor = generate_tuple_convertor(main_type.__args__)870 convertor = generate_tuple_convertor(get_args(main_type))871 if isinstance(parameter_info, OptionInfo):872 if main_type is bool and parameter_info.is_flag is not False:873 is_flag = True874 # Click doesn't accept a flag of type bool, only None, and then it sets it
146 unmodified lines
1021 args_name = None1022 incomplete_name = None1023 unassigned_params = list(parameters.values())1024 for param_sig in unassigned_params[:]:1023 origin = getattr(param_sig.annotation, "__origin__", None)1025 origin = get_origin(param_sig.annotation)1026 if lenient_issubclass(param_sig.annotation, click.Context):1027 ctx_name = param_sig.name1028 unassigned_params.remove(param_sig)1029 elif lenient_issubclass(origin, List):
41 unmodified lines