Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
64 commits
Select commit Hold shift + click to select a range
afc9cf4
Add option to use Enum names
sirex Jan 21, 2021
2e079f2
Fix black issues
sirex Jan 21, 2021
b0f534e
Fix isort issues
sirex Jan 21, 2021
2a18e31
Merge branch 'master' into enum-names
svlandeg Aug 14, 2024
5769c4a
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Aug 14, 2024
f4a99b2
rename 004 to 005
svlandeg Aug 14, 2024
0ce6ade
Merge branch 'enum-names' of https://github.com/sirex/typer into enum…
svlandeg Aug 14, 2024
5d63dbd
restore the original 003 as 004
svlandeg Aug 14, 2024
9a00cd9
Merge branch 'master' into enum-names
svlandeg Aug 16, 2024
2c9192f
Merge branch 'master' into enum-names
svlandeg Aug 19, 2024
ad046fc
Merge branch 'master' into enum-names
svlandeg Sep 11, 2024
a77dddd
fix issues
svlandeg Sep 11, 2024
dfaf7b3
rename to enum_by_name and fix the convertor code order
svlandeg Sep 11, 2024
d77ac5b
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Sep 11, 2024
c39a5ea
Add console example for IntEnum
svlandeg Sep 11, 2024
b77a29f
Merge remote-tracking branch 'upstream_sirex/enum-names' into enum-names
svlandeg Sep 11, 2024
8312bb8
Fix default values
svlandeg Sep 11, 2024
b5648ed
Add additional unit tests combining enums with list/tuple
svlandeg Sep 11, 2024
e24f446
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Sep 11, 2024
0644919
pass along enum_by_name parameter to generate_X_convertor functions
svlandeg Sep 11, 2024
478d183
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Sep 11, 2024
eee3a4c
add Annotated versions of the new tests
svlandeg Sep 11, 2024
b5bd589
Merge remote-tracking branch 'upstream_sirex/enum-names' into enum-names
svlandeg Sep 11, 2024
e2053b1
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Sep 11, 2024
221a865
ignore 006 tutorial just like 003 (mutable default argument)
svlandeg Sep 12, 2024
7b59934
update enum.md to use the annotated versions as well
svlandeg Sep 12, 2024
5759360
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Sep 12, 2024
87ae5ad
add tests with Argument
svlandeg Sep 12, 2024
e13a083
Merge remote-tracking branch 'upstream_sirex/enum-names' into enum-names
svlandeg Sep 12, 2024
adb7c03
fix printing of enum value (needed for Python 3.11 and 3.12)
svlandeg Sep 12, 2024
9ad26c2
remove lowercasing from generator function - should be done with case…
svlandeg Sep 12, 2024
6ae6c9b
🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
pre-commit-ci[bot] Sep 12, 2024
bfae3ef
fix hl_lines
svlandeg Sep 12, 2024
825b477
Merge branch 'master' into enum-names
svlandeg Aug 28, 2025
7f4f4e1
use new format
svlandeg Aug 28, 2025
c0107fb
fix
svlandeg Aug 28, 2025
857e2ea
fix tests by checking output instead of stdout
svlandeg Aug 28, 2025
4558ebf
Merge branch 'master' into enum-names
svlandeg Sep 1, 2025
8582aee
Merge branch 'master' into enum-names
svlandeg Oct 7, 2025
727f06c
move 007 to 004 to avoid conflict with master
svlandeg Oct 7, 2025
2a5e8c4
fix mod
svlandeg Oct 7, 2025
b33239e
Merge branch 'master' into enum-names
svlandeg Nov 25, 2025
3d6df84
update the tutorial examples to use explicit Typer() instance
svlandeg Nov 25, 2025
a18aea0
Merge branch 'master' into enum-names
svlandeg Jan 13, 2026
82ae00a
🎨 Auto format
pre-commit-ci-lite[bot] Jan 13, 2026
d516837
use tuple, type and list
svlandeg Jan 13, 2026
dc2cbac
update test format to latest from master
svlandeg Jan 27, 2026
a877e98
🎨 Auto format
pre-commit-ci-lite[bot] Jan 27, 2026
ccbac9c
Merge branch 'master' into enum-names
svlandeg Jan 28, 2026
04c68a6
fix lint and formatting
svlandeg Jan 28, 2026
445d4c3
Merge remote-tracking branch 'upstream_sirex/enum-names' into enum-names
svlandeg Jan 28, 2026
bf153ff
fix wrongly resolved merge conflict
svlandeg Jan 28, 2026
85e2a4b
fix docs
svlandeg Jan 28, 2026
dbce376
remove unnecessary (and unmentioned) extra files
svlandeg Jan 28, 2026
8f92309
Merge branch 'master' into enum-names
svlandeg Feb 14, 2026
0e62f69
🎨 Auto format
pre-commit-ci-lite[bot] Feb 14, 2026
cb75b2f
fix
svlandeg Feb 14, 2026
dfb1bc9
Merge remote-tracking branch 'upstream_sirex/enum-names' into enum-names
svlandeg Feb 14, 2026
cdffa1d
Merge branch 'master' into enum-names
svlandeg Feb 17, 2026
ced68ca
refactor to py310
svlandeg Feb 17, 2026
cacc67f
🎨 Auto format
pre-commit-ci-lite[bot] Feb 17, 2026
2ab49cf
Merge branch 'master' into enum-names
svlandeg Feb 17, 2026
406e291
format
svlandeg Feb 17, 2026
5ce497b
Merge branch 'master' into enum-names
svlandeg Feb 17, 2026
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
54 changes: 54 additions & 0 deletions docs/tutorial/parameter-types/enum.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,37 @@ Training neural network of type: lstm

</div>

### Using Enum names instead of values

Sometimes you want to accept `Enum` names from the command line and convert
that into `Enum` values in the command handler. You can enable this by setting
`enum_by_name=True`:

{* docs_src/parameter_types/enum/tutorial007_an_py310.py hl[18] *}

And then the names of the `Enum` can be used instead of values:

<div class="termy">

```console
$ python main.py --log-level debug

Log level set to DEBUG
```

</div>

This can be particularly useful if the enum values are not strings:

{* docs_src/parameter_types/enum/tutorial005_an_py310.py hl[8:11,18] *}

```console
$ python main.py --access protected

Access level: protected (2)
```


### List of Enum values

A *CLI parameter* can also take a list of `Enum` values:
Expand Down Expand Up @@ -112,6 +143,29 @@ Buying groceries: Eggs, Bacon

</div>

You can also combine `enum_by_name=True` with a list of enums:

{* docs_src/parameter_types/enum/tutorial006_an_py310.py hl[18] *}

This works exactly the same, but you're using the enum names instead of values:

<div class="termy">

```console
// Try it with a single value
$ python main.py --groceries "f1"

Buying groceries: Eggs

// Try it with multiple values
$ python main.py --groceries "f1" --groceries "f2"

Buying groceries: Eggs, Bacon
```

</div>


### Literal choices

You can also use `Literal` to represent a set of possible predefined choices, without having to use an `Enum`:
Expand Down
23 changes: 23 additions & 0 deletions docs_src/parameter_types/enum/tutorial005_an_py310.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import enum
from typing import Annotated

import typer


class Access(enum.IntEnum):
private = 1
protected = 2
public = 3
open = 4


app = typer.Typer()


@app.command()
def main(access: Annotated[Access, typer.Option(enum_by_name=True)] = "private"):
typer.echo(f"Access level: {access.name} ({access.value})")


if __name__ == "__main__":
app()
22 changes: 22 additions & 0 deletions docs_src/parameter_types/enum/tutorial005_py310.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import enum

import typer


class Access(enum.IntEnum):
private = 1
protected = 2
public = 3
open = 4


app = typer.Typer()


@app.command()
def main(access: Access = typer.Option("private", enum_by_name=True)):
typer.echo(f"Access level: {access.name} ({access.value})")


if __name__ == "__main__":
app()
24 changes: 24 additions & 0 deletions docs_src/parameter_types/enum/tutorial006_an_py310.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from enum import Enum
from typing import Annotated

import typer


class Food(str, Enum):
f1 = "Eggs"
f2 = "Bacon"
f3 = "Cheese"


app = typer.Typer()


@app.command()
def main(
groceries: Annotated[list[Food], typer.Option(enum_by_name=True)] = ["f1", "f3"],
):
print(f"Buying groceries: {', '.join([f.value for f in groceries])}")


if __name__ == "__main__":
app()
21 changes: 21 additions & 0 deletions docs_src/parameter_types/enum/tutorial006_py310.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from enum import Enum

import typer


class Food(str, Enum):
f1 = "Eggs"
f2 = "Bacon"
f3 = "Cheese"


app = typer.Typer()


@app.command()
def main(groceries: list[Food] = typer.Option(["f1", "f3"], enum_by_name=True)):
print(f"Buying groceries: {', '.join([f.value for f in groceries])}")


if __name__ == "__main__":
app()
23 changes: 23 additions & 0 deletions docs_src/parameter_types/enum/tutorial007_an_py310.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import enum
import logging
from typing import Annotated

import typer


class LogLevel(enum.Enum):
debug = logging.DEBUG
info = logging.INFO
warning = logging.WARNING


app = typer.Typer()


@app.command()
def main(log_level: Annotated[LogLevel, typer.Option(enum_by_name=True)] = "warning"):
typer.echo(f"Log level set to: {logging.getLevelName(log_level.value)}")


if __name__ == "__main__":
app()
22 changes: 22 additions & 0 deletions docs_src/parameter_types/enum/tutorial007_py310.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import enum
import logging

import typer


class LogLevel(enum.Enum):
debug = logging.DEBUG
info = logging.INFO
warning = logging.WARNING


app = typer.Typer()


@app.command()
def main(log_level: LogLevel = typer.Option("warning", enum_by_name=True)):
typer.echo(f"Log level set to: {logging.getLevelName(log_level.value)}")


if __name__ == "__main__":
app()
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ ignore = [
"docs_src/options_autocompletion/tutorial008_an_py310.py" = ["B006"]
"docs_src/options_autocompletion/tutorial009_an_py310.py" = ["B006"]
"docs_src/parameter_types/enum/tutorial003_an_py310.py" = ["B006"]
"docs_src/parameter_types/enum/tutorial006_an_py310.py" = ["B006"]
# Loop control variable `value` not used within loop body
"docs_src/progressbar/tutorial001_py310.py" = ["B007"]
"docs_src/progressbar/tutorial003_py310.py" = ["B007"]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import importlib
import subprocess
import sys
from types import ModuleType

import pytest
from typer.testing import CliRunner

runner = CliRunner()


@pytest.fixture(
name="mod",
params=[
pytest.param("tutorial005_py310"),
pytest.param("tutorial005_an_py310"),
],
)
def get_mod(request: pytest.FixtureRequest) -> ModuleType:
module_name = f"docs_src.parameter_types.enum.{request.param}"
mod = importlib.import_module(module_name)
return mod


def test_int_enum_default(mod: ModuleType):
result = runner.invoke(mod.app)
assert result.exit_code == 0
assert "Access level: private (1)" in result.output


def test_int_enum(mod: ModuleType):
result = runner.invoke(mod.app, ["--access", "open"])
assert result.exit_code == 0
assert "Access level: open (4)" in result.output


def test_script(mod: ModuleType):
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,57 @@
import importlib
import subprocess
import sys
from types import ModuleType

import pytest
from typer.testing import CliRunner

runner = CliRunner()


@pytest.fixture(
name="mod",
params=[
pytest.param("tutorial006_py310"),
pytest.param("tutorial006_an_py310"),
],
)
def get_mod(request: pytest.FixtureRequest) -> ModuleType:
module_name = f"docs_src.parameter_types.enum.{request.param}"
mod = importlib.import_module(module_name)
return mod


def test_help(mod: ModuleType):
result = runner.invoke(mod.app, ["--help"])
assert result.exit_code == 0
assert "--groceries" in result.output
assert "[f1|f2|f3]" in result.output
assert "default: f1, f3" in result.output


def test_call_no_arg(mod: ModuleType):
result = runner.invoke(mod.app)
assert result.exit_code == 0
assert "Buying groceries: Eggs, Cheese" in result.output


def test_call_single_arg(mod: ModuleType):
result = runner.invoke(mod.app, ["--groceries", "f2"])
assert result.exit_code == 0
assert "Buying groceries: Bacon" in result.output


def test_call_multiple_arg(mod: ModuleType):
result = runner.invoke(mod.app, ["--groceries", "f1", "--groceries", "f2"])
assert result.exit_code == 0
assert "Buying groceries: Eggs, Bacon" in result.output


def test_script(mod: ModuleType):
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,43 @@
import importlib
import subprocess
import sys
from types import ModuleType

import pytest
from typer.testing import CliRunner

runner = CliRunner()


@pytest.fixture(
name="mod",
params=[
pytest.param("tutorial007_py310"),
pytest.param("tutorial007_an_py310"),
],
)
def get_mod(request: pytest.FixtureRequest) -> ModuleType:
module_name = f"docs_src.parameter_types.enum.{request.param}"
mod = importlib.import_module(module_name)
return mod


def test_enum_names_default(mod: ModuleType):
result = runner.invoke(mod.app)
assert result.exit_code == 0
assert "Log level set to: WARNING" in result.output


def test_enum_names(mod: ModuleType):
result = runner.invoke(mod.app, ["--log-level", "debug"])
assert result.exit_code == 0
assert "Log level set to: DEBUG" in result.output


def test_script(mod: ModuleType):
result = subprocess.run(
[sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],
capture_output=True,
encoding="utf-8",
)
assert "Usage" in result.stdout
Loading