Enum Arguments/Options with custom click_type are always None #777
-
First Check
Commit to Help
Example Codeimport enum
from typing import Any, Optional
import click
import typer
from typer.testing import CliRunner
def test_custom_click_type_enum():
class OnlyOneCatEnum(enum.Enum):
CAT = "cat"
class NoPluralCatsChoice(click.Choice):
name = "single_cat"
def convert(
self,
value: Any,
param: Optional[click.Parameter],
ctx: Optional[click.Context],
) -> Any:
if value.endswith("s"):
value = value[:-1]
return OnlyOneCatEnum(value)
app = typer.Typer()
@app.command()
def custom_click_type_enum(
ctx: typer.Context,
animal: OnlyOneCatEnum = typer.Argument(
None, click_type=NoPluralCatsChoice(choices=["cat"])
),
animal_option: OnlyOneCatEnum = typer.Option(
None, click_type=NoPluralCatsChoice(choices=["cat"])
),
):
assert (
ctx.params["animal"] == OnlyOneCatEnum.CAT
), "The animal param was not a cat!"
assert (
ctx.params["animal_option"] == OnlyOneCatEnum.CAT
), "The animal_option param was not a cat!"
assert animal == OnlyOneCatEnum.CAT, "The animal Argument was not a cat!"
assert (
animal_option == OnlyOneCatEnum.CAT
), "The animal_option Option was not a cat!"
result = CliRunner().invoke(app, ["cats", "--animal-option", "cats"])
assert result.exit_code == 0 DescriptionWhen I define a custom Click type using Enums and set the
This does not appear to happen with Click, where the relevant piece of code becomes: @click.command()
@click.argument("animal", type=NoPluralCatsChoice(["cats"]))
@click.option("--animal-option", type=NoPluralCatsChoice(["cats"]))
@click.pass_context
def custom_click_type_enum(
ctx: click.Context,
animal: NoPluralCatsChoice,
animal_option: NoPluralCatsChoice,
):
assert animal == OnlyOneCatEnum.CAT, "The animal Argument was not a cat!"
assert (
animal_option == OnlyOneCatEnum.CAT
), "The animal_option Option was not a cat!"
result = CliRunner().invoke(
custom_click_type_enum, ["cats", "--animal-option", "cats"]
)
assert result.exit_code == 0 Operating SystemmacOS Operating System DetailsNo response Typer Version0.11.0 Python VersionPython 3.10.12 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
If you return The issue is that |
Beta Was this translation helpful? Give feedback.
If you return
value
rather thanOnlyOneCatEnum(value)
fromNoPluralCatsChoice.convert()
, thenanimal
andanimal_option
will correctly contain the enum instanceOnlyOneCatEnum.CAT
andctx.params
will contain the stringcat
, which is the intended behavior I believe.The issue is that
click.Choice
is not expectingconvert()
to return an instance of an enum. When typer creates aclick.Choice
under the hood, it passes only with the values of the enum (and the enum is only dealt with in typer):https://github.com/tiangolo/typer/blob/968d81df54997fa0219ca2de2aeacbab54daa003/typer/main.py#L779-L783