paul j3 added the comment:

The `type` parameter is a *function* that takes a string, and returns a valid 
value.  If it can't convert the string it is supposed to raise an error.  The 
default one is a do-nothing identity (take a string, return the string).  `int` 
is the Python function that converts a string to an integer.  Same for `float`.

Your example could be implemented with a simple type function:

    def enumtype(astring):
        try:
            return CustomEnumType[astring.upper()]
        except KeyError:
            raise argparse.ArgumentError()

    parser=argparse.ArgumentParser()
    parser.add_argument("-p", type=enumtype, default="VAL1")

    print(parser.parse_args([]))
    print(parser.parse_args(["-p","val2"]))
    print(parser.parse_args(["-p","val4"]))

which produces:

    1557:~/mypy$ python3 issue25061.py
    Namespace(p=<CustomEnumType.VAL1: 1>)
    Namespace(p=<CustomEnumType.VAL2: 2>)
    usage: issue25061.py [-h] [-p P]
    issue25061.py: error: argument -p: invalid enumtype value: 'val4'


The default and 'val2' produce enum values in the Namespace.

'val4' raises an error, resulting in the usage and error message.

I tried to customize the error message to include the list of valid strings, 
but it looks like I'll have to dig into the calling tree to do that right.  
Still the default message is useful, displaying the name of the 'type' function.

If we were to add 'enum' support it would have to be something like 
'argparse.FileType', a factory class that would take an enum class as 
parameter, and create a function like my sample.

----------
nosy: +paul.j3

_______________________________________
Python tracker <rep...@bugs.python.org>
<http://bugs.python.org/issue25061>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to