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 paul.j3
Recipients barry, desbma, paul.j3
Date 2015-09-10.23:24:53
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1441927493.84.0.154136637297.issue25061@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2015-09-10 23:24:53paul.j3setrecipients: + paul.j3, barry, desbma
2015-09-10 23:24:53paul.j3setmessageid: <1441927493.84.0.154136637297.issue25061@psf.upfronthosting.co.za>
2015-09-10 23:24:53paul.j3linkissue25061 messages
2015-09-10 23:24:53paul.j3create