Skip to content

argparse: allow to override the type name in 'invalid %(type)s value: %(value)r' error messages #122679

Closed
@calestyo

Description

@calestyo

Feature or enhancement

Proposal:

Hey.

When doing something like:

class SomeEnumClass(enum.StrEnum):
    foo = enum.auto()
    bar = enum.auto()

parser.add_argument("--enum", type=SomeEnumClass, choices=[e.value  for e in SomeEnumClass])

and calls --enum with argument baz, it will error out with a message like:

my.py: error: argument --enum: invalid SomeEnumClass value: 'baz'

via:

msg = _('invalid %(type)s value: %(value)r')

For the end user (who sees this message), the SomeEnumClass-part may be rather useless, as it may be some arbitrary internal class name, which may or may not be related to the option.

So in principle I think one should be able to configure a string to be printed instead of SomeEnumClass.

One candidate would be of course metavar, but the problem with that is, that if one sets it, the --help-text would be different, too, and not longer print the choices, but rather the metavar, which one may not want.

The only way I've found to get that without extending argparse is:

class SomeEnumClass(enum.StrEnum):
    foo = enum.auto()
    bar = enum.auto()
SomeEnumClass.__name__ = "blubb"

which causes:

my.py: error: argument --enum: invalid blubb value: 'baz'

to be printed,... but I guess is rather not really well defined, or is it?

Cheers,
Chris.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Labels

docsDocumentation in the Doc dir

Projects

Status

Doc issues

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions