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 preserving case in enum values #571

Merged
merged 18 commits into from
Mar 23, 2024
Merged
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
8 changes: 8 additions & 0 deletions docs/tutorial/parameter-types/enum.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,14 @@ Usage: main.py [OPTIONS]
Try "main.py --help" for help.

Error: Invalid value for '--network': invalid choice: capsule. (choose from simple, conv, lstm)

// Note that enums are case sensitive by default
$ python main.py --network CONV

Usage: main.py [OPTIONS]
Try "main.py --help" for help.

Error: Invalid value for '--network': invalid choice: CONV. (choose from simple, conv, lstm)
```

</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,22 @@ def test_main():
assert "Training neural network of type: conv" in result.output


def test_invalid():
def test_invalid_case():
result = runner.invoke(app, ["--network", "CONV"])
assert result.exit_code != 0
# TODO: when deprecating Click 7, remove second option

assert (
"Invalid value for '--network': 'CONV' is not one of" in result.output
or "Invalid value for '--network': invalid choice: CONV. (choose from"
in result.output
)
assert "simple" in result.output
assert "conv" in result.output
assert "lstm" in result.output


def test_invalid_other():
result = runner.invoke(app, ["--network", "capsule"])
assert result.exit_code != 0
# TODO: when deprecating Click 7, remove second option
Expand Down
8 changes: 4 additions & 4 deletions typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,13 +618,13 @@ def param_path_convertor(value: Optional[str] = None) -> Optional[Path]:


def generate_enum_convertor(enum: Type[Enum]) -> Callable[[Any], Any]:
lower_val_map = {str(val.value).lower(): val for val in enum}
val_map = {str(val.value): val for val in enum}

def convertor(value: Any) -> Any:
if value is not None:
low = str(value).lower()
if low in lower_val_map:
key = lower_val_map[low]
val = str(value)
if val in val_map:
key = val_map[val]
return enum(key)

return convertor
Expand Down
Loading