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 all 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
48 changes: 48 additions & 0 deletions docs/tutorial/parameter-types/enum.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,51 @@ Buying groceries: Eggs, Bacon
```

</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 3.7+"

```Python hl_lines="6"
{!> ../docs_src/parameter_types/enum/tutorial004_an.py!}
```

=== "Python 3.7+ non-Annotated"

!!! tip
Prefer to use the `Annotated` version if possible.

```Python hl_lines="5"
{!> ../docs_src/parameter_types/enum/tutorial004.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]
--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': 'capsule' is not one of 'simple', 'conv', 'lstm'.
```

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


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


if __name__ == "__main__":
typer.run(main)
12 changes: 12 additions & 0 deletions docs_src/parameter_types/enum/tutorial004_an.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import typer
from typing_extensions import Annotated, Literal


def main(
network: Annotated[Literal["simple", "conv", "lstm"], typer.Option()] = "simple",
):
print(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,52 @@
import subprocess
import sys

import typer
from typer.testing import CliRunner

from docs_src.parameter_types.enum import tutorial004 as mod

from ....utils import needs_py38

runner = CliRunner()

app = typer.Typer()
app.command()(mod.main)


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


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


@needs_py38
def test_invalid():
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


@needs_py38
def test_script():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],
capture_output=True,
encoding="utf-8",
)
assert "Usage" in result.stdout
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import subprocess
import sys

import typer
from typer.testing import CliRunner

from docs_src.parameter_types.enum import tutorial004_an as mod

from ....utils import needs_py38

runner = CliRunner()

app = typer.Typer()
app.command()(mod.main)


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


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


@needs_py38
def test_invalid():
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


@needs_py38
def test_script():
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],
capture_output=True,
encoding="utf-8",
)
assert "Usage" in result.stdout
1 change: 1 addition & 0 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
except ShellDetectionFailure: # pragma: no cover
shell = None

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

needs_py310 = pytest.mark.skipif(
sys.version_info < (3, 10), reason="requires python3.10+"
Expand Down
7 changes: 6 additions & 1 deletion typer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import click
from typing_extensions import get_args, get_origin

from ._typing import is_union
from ._typing import is_literal_type, is_union, literal_values
from .completion import get_completion_inspect_parameters
from .core import (
DEFAULT_MARKUP_MODE,
Expand Down Expand Up @@ -797,6 +797,11 @@ def get_click_type(
[item.value for item in annotation],
case_sensitive=parameter_info.case_sensitive,
)
elif is_literal_type(annotation):
return click.Choice(
literal_values(annotation),
case_sensitive=parameter_info.case_sensitive,
)
raise RuntimeError(f"Type not yet supported: {annotation}") # pragma: no cover


Expand Down
Loading