Skip to content

Must use typer.Option to supply default argument with Enums created with functional API #389

@Torvaney

Description

@Torvaney

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the Typer documentation, with the integrated search.
  • I already searched in Google "How to X in Typer" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to Typer but to Click.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

import enum
import typer

Choice = enum.Enum('Choice', {k: k for k in ['first', 'second']})

def main(option: Choice = Choice.first):
    pass

typer.run(main)

# Usage: typer_reprex.py [OPTIONS]
# Try 'typer_reprex.py --help' for help.
# 
# Error: Invalid value for '--option': <Choice.first: 'first'> is not one of 'first', 'second'.

Description

When an enum is created via the functional API (as above), it cannot be used as a choice constraint, because it won't also subclass str.

In the documentation, choices are created by subclassing both str and enum.Enum. For example:

class Choice(str, Enum):
    first = 'first'
    second = 'second'

However, as far as I know, this isn't possible when using the functional API to create enums.

This can be worked around by supplying typer.Option with the default argument instead:

def main(option: Choice = typer.Option('first')):
    pass

While the workaround is very simple and non-obstructive, it's not clear from the docs that this is the case.

Operating System

macOS

Operating System Details

No response

Typer Version

0.4.1

Python Version

3.7.2

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions