| 1 |
.. _Typer Choices: |
| 2 |
|
| 3 |
======= |
| 4 |
Choices |
| 5 |
======= |
| 6 |
|
| 7 |
---- |
| 8 |
Enum |
| 9 |
---- |
| 10 |
Frequently, a CLI will want to limit values provided to a parameter to a specific set of choices. |
| 11 |
With Typer, this is accomplished via declaring an :class:`~enum.Enum`. |
| 12 |
|
| 13 |
.. code-block:: python |
| 14 |
|
| 15 |
import typer |
| 16 |
from enum import Enum |
| 17 |
|
| 18 |
class Environment(str, Enum): |
| 19 |
# Values end in "_value" to avoid confusion in this example. |
| 20 |
DEV = "dev_value" |
| 21 |
STAGING = "staging_value" |
| 22 |
PROD = "prod_value" |
| 23 |
|
| 24 |
typer_app = typer.Typer() |
| 25 |
|
| 26 |
@typer_app.command |
| 27 |
def foo(env: Environment = Environment.DEV): |
| 28 |
print(f"Using: {env.name}") |
| 29 |
|
| 30 |
print("Typer (Enum):") |
| 31 |
typer_app(["--env", "staging_value"]) |
| 32 |
# Using: STAGING |
| 33 |
|
| 34 |
Typer looks for the CLI-provided *value*, and supplies the function with the enum member. |
| 35 |
IMHO, this is backwards; typically the enum name (e.g. ``DEV``) is intended to be more human-friendly, while the value (e.g. ``dev_value``) more frequently has a programmatic-meaning. **When using enums, Cyclopts will do the opposite of Typer**, performing a **case-insensitive** lookup by **name**. |
| 36 |
|
| 37 |
.. code-block:: python |
| 38 |
|
| 39 |
import cyclopts |
| 40 |
|
| 41 |
cyclopts_app = cyclopts.App() |
| 42 |
|
| 43 |
@cyclopts_app.default |
| 44 |
def foo(env: Environment = Environment.DEV): |
| 45 |
print(f"Using: {env.name}") |
| 46 |
|
| 47 |
print("Cyclopts (Enum):") |
| 48 |
cyclopts_app(["--env", "staging"]) |
| 49 |
# Using: STAGING |
| 50 |
|
| 51 |
------- |
| 52 |
Literal |
| 53 |
------- |
| 54 |
Enums don't work well with everyone's workflow. |
| 55 |
Many people prefer to directly use strings for their functions' options. |
| 56 |
The much more intuitive, convenient method of doing this is with the :obj:`~typing.Literal` type annotation. |
| 57 |
|
| 58 |
.. note:: |
| 59 |
|
| 60 |
Typer added support for :obj:`~typing.Literal` in version 0.19.0 (September 2025), resolving `a feature request from early 2020`_. |
| 61 |
|
| 62 |
Cyclopts has builtin support for :obj:`~typing.Literal`, see :ref:`Coercion Rules - Literal <Coercion Rules - Literal>`. |
| 63 |
|
| 64 |
.. code-block:: python |
| 65 |
|
| 66 |
import cyclopts |
| 67 |
from typing import Literal |
| 68 |
|
| 69 |
cyclopts_app = cyclopts.App() |
| 70 |
|
| 71 |
@cyclopts_app.default |
| 72 |
def foo(env: Literal["dev", "staging", "prod"] = "staging"): |
| 73 |
print(f"Using: {env}") |
| 74 |
|
| 75 |
|
| 76 |
print("Cyclopts (Literal):") |
| 77 |
cmd = ["--env", "staging"] |
| 78 |
print(cmd) |
| 79 |
cyclopts_app(cmd) |
| 80 |
# Using: staging |
| 81 |
|
| 82 |
.. _a feature request from early 2020: https://github.com/tiangolo/typer/issues/76 |