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

✨ Support typing.Literal in Python 3.8+ #429

Open
wants to merge 29 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
09d56ba
Support for typing.Literal as an alternative to Enum in Python 3.8+.
dwalters Oct 8, 2020
4e2e714
Merge branch 'master' into support_literal_choices
blackary Jul 14, 2022
d83f792
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Jul 14, 2022
095e064
Correct test to handle space in output
blackary Jul 14, 2022
7a3466d
Merge branch 'master' into support_literal_choices
tiangolo Dec 16, 2022
1e261e6
Merge branch 'master' into support_literal_choices
blackary Dec 21, 2022
847e634
Rename to tutorial004 to avoid conflict with master branch
svlandeg Jun 3, 2024
f8f381a
Add version with Annotated
svlandeg Jun 3, 2024
655a801
Merge branch 'master' into support_literal_choices
svlandeg Jun 3, 2024
89b87fe
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Jun 3, 2024
d4cd3c3
Fix
svlandeg Jun 3, 2024
1f4b6dd
@needs_py38 fixture
svlandeg Jun 3, 2024
c7dd353
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Jun 3, 2024
9fe6ad8
further updates
svlandeg Jun 3, 2024
bee8230
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Jun 3, 2024
288318b
use _typing module
svlandeg Jun 3, 2024
5d82c10
Merge remote-tracking branch 'upstream_blackary/support_literal_choic…
svlandeg Jun 3, 2024
2d62d19
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Jun 3, 2024
01d8013
import Literal from typing_extensions
svlandeg Jun 3, 2024
6065329
fix highlighted lines for documentation
svlandeg Jun 3, 2024
3b9034b
update console output
svlandeg Jun 3, 2024
2bacd29
fix import statement to be relative
svlandeg Jun 10, 2024
a771189
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Jun 10, 2024
74a6116
Merge branch 'master' into support_literal_choices
svlandeg Aug 9, 2024
c29c5d2
Merge branch 'master' into support_literal_choices
svlandeg Aug 19, 2024
cb93aa4
Merge branch 'master' into support_literal_choices
svlandeg Aug 26, 2024
1834fb8
Merge branch 'master' into support_literal_choices
svlandeg Sep 2, 2024
f06dcf5
Merge branch 'master' into support_literal_choices
svlandeg Sep 2, 2024
20b55f6
Merge branch 'master' into support_literal_choices
svlandeg Sep 2, 2024
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
38 changes: 38 additions & 0 deletions docs/tutorial/parameter-types/enum.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,41 @@ Training neural network of type: lstm
```

</div>

### Literal choices

With Python 3.8+, you can also use `typing.Literal` to represent a set of possible predefined choices, without having to use an `Enum`:

```Python hl_lines="13"
{!../docs_src/parameter_types/enum/tutorial003.py!}
```

<div class="termy">

```console
$ python main.py --help

// Notice the predefined values [simple|conv|lstm]
Usage: main.py [OPTIONS]

Options:
--network [simple|conv|lstm] [default: simple]
--install-completion Install completion for the current shell.
--show-completion Show completion for the current shell, to copy it or customize the installation.
--help Show this message and exit.

// Try it
$ python main.py --network conv

Training neural network of type: conv

// Invalid value
$ python main.py --network capsule

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

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

</div>
11 changes: 11 additions & 0 deletions docs_src/parameter_types/enum/tutorial003.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from typing import Literal

import typer


def main(network: Literal["simple", "conv", "lstm"] = "simple"):
typer.echo(f"Training neural network of type: {network}")


if __name__ == "__main__":
typer.run(main)
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import subprocess
import sys

import pytest
import typer
from typer.testing import CliRunner

pytestmark = pytest.mark.skipif(sys.version_info < (3, 8), reason="requires python3.8")


runner = CliRunner()


@pytest.fixture(scope="module")
def mod():
from docs_src.parameter_types.enum import tutorial003 as mod

return mod


@pytest.fixture(scope="module")
def app(mod):
app = typer.Typer()
app.command()(mod.main)
return app


def test_help(app):
result = runner.invoke(app, ["--help"])
assert result.exit_code == 0
assert "--network [simple|conv|lstm]" in result.output.replace(" ", "")


def test_main(app):
result = runner.invoke(app, ["--network", "conv"])
assert result.exit_code == 0
assert "Training neural network of type: conv" in result.output


def test_invalid(app):
result = runner.invoke(app, ["--network", "capsule"])
assert result.exit_code != 0
assert (
"Invalid value for '--network': invalid choice: capsule. (choose from"
in result.output
or "Invalid value for '--network': 'capsule' is not one of" in result.output
)
assert "simple" in result.output
assert "conv" in result.output
assert "lstm" in result.output


def test_script(mod):
result = subprocess.run(
["coverage", "run", mod.__file__, "--help"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
)
assert "Usage" in result.stdout
6 changes: 6 additions & 0 deletions typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
import sys
import traceback
import typing
from datetime import datetime
from enum import Enum
from functools import update_wrapper
Expand Down Expand Up @@ -770,6 +771,11 @@ def get_click_type(
[item.value for item in annotation],
case_sensitive=parameter_info.case_sensitive,
)
elif sys.version_info >= (3, 8) and typing.get_origin(annotation) == typing.Literal:
return click.Choice(
tuple(typing.get_args(annotation)),
case_sensitive=parameter_info.case_sensitive,
)
raise RuntimeError(f"Type not yet supported: {annotation}") # pragma no cover


Expand Down