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 the Enum behaviour with Literal #106

Closed
carmocca opened this issue Nov 30, 2021 · 3 comments
Closed

Support the Enum behaviour with Literal #106

carmocca opened this issue Nov 30, 2021 · 3 comments
Labels
enhancement New feature or request

Comments

@carmocca
Copy link
Contributor

carmocca commented Nov 30, 2021

It would be nice if jsonargparse supported choices with typing.Literal.

So this script:

from typing import Union

import jsonargparse
from typing_extensions import Literal


def fn(choice: Union[Literal["A"], Literal["B"]]):
    if choice == "A":
        ...
    elif choice == "B":
        ...

parser = jsonargparse.ArgumentParser()
parser.add_function_arguments(fn)
parser.print_help()
<function fn at 0x10be09550>:
  --choice CHOICE  (required, type: Union[Literal['A'], Literal['B']])

would be equal to

from enum import Enum

import jsonargparse


class Choice(str, Enum):
    A = "A"
    B = "B"


def fn(choice: Choice):
    if choice == "A":
        ...
    elif choice == "B":
        ...

parser = jsonargparse.ArgumentParser()
parser.add_function_arguments(fn)
parser.print_help()
<function fn at 0x109aab550>:
  --choice {A,B}  (required, type: Choice)

with the better help message and input validation

@mauvilsa mauvilsa added the enhancement New feature or request label Dec 2, 2021
@mauvilsa
Copy link
Member

From what I see the validation of Literal works as expected, so I am a bit confused with "the better ... and input validation". This seems to be just a request to change the help message. And the only difference would be that instead of CHOICE it would be {A,B}. Correct?

@carmocca
Copy link
Contributor Author

Yes 😄

mauvilsa added a commit that referenced this issue May 30, 2022
- tuple metavar now shown as [ITEM,...].
- Required arguments with None default now shown without brackets in usage.
- Improved description of --print_config in help.
- Applied pyupgrade --py36-plus and did some minor refactorings.
- Added issue templates.
@mauvilsa
Copy link
Member

This is now done. However, note that it has been done for a type hint like Literal["A", "B"]. Having a union of individual literals shouldn't be used and makes no sense to have special support for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants