File tree Expand file tree Collapse file tree 2 files changed +34
-1
lines changed Expand file tree Collapse file tree 2 files changed +34
-1
lines changed Original file line number Diff line number Diff line change
1
+ from enum import Enum
2
+ from typing import Generic , TypeVar , Union
3
+
4
+ import click
5
+
6
+ ParamTypeValue = TypeVar ("ParamTypeValue" )
7
+
8
+
9
+ class TyperChoice (click .Choice , Generic [ParamTypeValue ]): # type: ignore[type-arg]
10
+ def normalize_choice (
11
+ self , choice : ParamTypeValue , ctx : Union [click .Context , None ]
12
+ ) -> str :
13
+ # Click 8.2.0 added a new method `normalize_choice` to the `Choice` class
14
+ # to support enums, but it uses the enum names, while Typer has always used the
15
+ # enum values.
16
+ # This class overrides that method to maintain the previous behavior.
17
+ # In Click:
18
+ # normed_value = choice.name if isinstance(choice, Enum) else str(choice)
19
+ normed_value = choice .value if isinstance (choice , Enum ) else str (choice )
20
+
21
+ if ctx is not None and ctx .token_normalize_func is not None :
22
+ normed_value = ctx .token_normalize_func (normed_value )
23
+
24
+ if not self .case_sensitive :
25
+ normed_value = normed_value .casefold ()
26
+
27
+ return normed_value
Original file line number Diff line number Diff line change 15
15
from uuid import UUID
16
16
17
17
import click
18
+ from typer ._types import TyperChoice
18
19
19
20
from ._typing import get_args , get_origin , is_union
20
21
from .completion import get_completion_inspect_parameters
@@ -787,7 +788,12 @@ def get_click_type(
787
788
atomic = parameter_info .atomic ,
788
789
)
789
790
elif lenient_issubclass (annotation , Enum ):
790
- return click .Choice (
791
+ # The custom TyperChoice is only needed for Click < 8.2.0, to parse the
792
+ # command line values matching them to the enum values. Click 8.2.0 added
793
+ # support for enum values but reading enum names.
794
+ # Passing here the list of enum values (instead of just the enum) accounts for
795
+ # Click < 8.2.0.
796
+ return TyperChoice (
791
797
[item .value for item in annotation ],
792
798
case_sensitive = parameter_info .case_sensitive ,
793
799
)
You can’t perform that action at this time.
0 commit comments