This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author shangxiao
Recipients paul.j3, rhettinger, shangxiao, xtreak
Date 2020-11-29.13:39:11
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <[email protected]>
In-reply-to
Content
Oh apologies, I had "open" selected when I searched for prior issues.

Upon reading that issue I agree with Mr Hettinger's points about enum values not being a concern of the parser.

The solution for my needs was simple enough: I made my own action which simply set choices based on member values (I'm using user-friendly strings) and converted to the correct type upon being called [1].

Instead of removing any mention of enums from the docs - would a small example showing how to deal with them be worthwhile?


[1]
def enum_action_factory(enum_class):

    class EnumAction(argparse.Action):
        def __init__(self, option_strings, dest, **kwargs):
            kwargs["choices"] = [member.value for member in enum_class]
            super().__init__(option_strings, dest, **kwargs)

        def __call__(self, parser, namespace, values, option_string):
            if isinstance(values, str):
                converted_values = enum_class(values)
            else:
                converted_values = [enum_class(value) for value in values]
            setattr(namespace, self.dest, converted_values)

    return EnumAction
History
Date User Action Args
2020-11-29 13:39:12shangxiaosetrecipients: + shangxiao, rhettinger, paul.j3, xtreak
2020-11-29 13:39:12shangxiaosetmessageid: <[email protected]>
2020-11-29 13:39:12shangxiaolinkissue42501 messages
2020-11-29 13:39:11shangxiaocreate