[issue9625] argparse: Problem with defaults for variable nargs when using choices

João Eiras report at bugs.python.org
Fri Jul 12 08:55:53 EDT 2019


João Eiras <joao.eiras at gmail.com> added the comment:

Another workaround for who might ever need it. The benefit of this solution comparing to a custom type is that argparse will generate the help string properly with the choices, and this solution does workaround the place when the bug happens:

    class Choices(tuple):
        # Python bug https://bugs.python.org/issue27227
        def __new__(cls, *args, **kwargs):
            x = tuple.__new__(cls, *args, **kwargs)
            Choices.__init__(x, *args, **kwargs)
            return x

        def __init__(self, *args, **kwargs):
            self.default = []

        def __contains__(self, item):
            return tuple.__contains__(self, item) or item is self.default

    choices = Choices(("value1", "value2", "value3", ...))

    parser.add_argument(
        ...,
        nargs="*",
        choices=choices,
        default=choices.default,
        ...)

----------
nosy: +João Eiras

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue9625>
_______________________________________


More information about the Python-bugs-list mailing list