🐛 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
Provenance
- Commit
218bf89- Tree
75d61c7- Author
Jonas L. B. <drixi.b@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
ad421bd
2 files changed+37 added−13 removed
modified:tests/test_type_conversion.py+22 added
5 unmodified lines6 import pytest7 import typer8 from typer.testing import CliRunner9 10+from .utils import needs_py31011+12 runner = CliRunner()13 14 15 def test_optional():14 unmodified lines30 assert result.exit_code == 031 assert "User: Camila" in result.output32 33 34+@needs_py31035+def test_union_type_optional():36+ app = typer.Typer()37+38+ @app.command()39+ def opt(user: str | None = None):40+ if user:41+ print(f"User: {user}")42+ else:43+ print("No user")44+45+ result = runner.invoke(app)46+ assert result.exit_code == 047+ assert "No user" in result.output48+49+ result = runner.invoke(app, ["--user", "Camila"])50+ assert result.exit_code == 051+ assert "User: Camila" in result.output52+53+54 def test_optional_tuple():55 app = typer.Typer()56 57 @app.command()114 unmodified linesmodified:typer/main.py+15 added-13 removed
11 unmodified lines12 from uuid import UUID13 14 import click15 16+from ._typing import get_args, get_origin, is_union17 from .completion import get_completion_inspect_parameters18 from .core import MarkupMode, TyperArgument, TyperCommand, TyperGroup, TyperOption19 from .models import (20 AnyType,804 unmodified lines825 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)830+831 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 lines866 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 it146 unmodified lines1021 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