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-14.20:56:17
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1442264177.81.0.0770566960303.issue25061@psf.upfronthosting.co.za>
In-reply-to
Content
Here's a EnumType factory class, modeled on FileType.  

class EnumType(object):
    """Factory for creating enum object types
    """
    def __init__(self, enumclass):
        self.enums = enumclass

    def __call__(self, astring):
        name = self.enums.__name__
        try:
            return self.enums[astring.upper()]
        except KeyError:
            msg = ', '.join([t.name.lower() for t in self.enums])
            msg = '%s: use one of {%s}'%(name, msg)
            raise argparse.ArgumentTypeError(msg)

    def __repr__(self):
        astr = ', '.join([t.name.lower() for t in self.enums])
        return '%s(%s)' % (self.enums.__name__, astr)

It would be used like:

    parser=argparse.ArgumentParser()
    parser.add_argument("-p", type=EnumType(CustomEnumType),
        default="VAL1", help = 'type info: %(type)s')
    
'EnumType(CustomEnumType)' is as close as we are going to get to 'simply passing the enum' to the parser, given the current 'type' syntax.  This statement produces a callable object, the equivalent of my previous function.

By giving the class a `__repr__` it can also be used in the 'help' with the '%(type)s' syntax.  That's the main functionality that this factory adds to my previous function definition.

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


produces

    usage: issue25061.py [-h] [-p P]
    optional arguments:
        -h, --help  show this help message and exit
        -p P        type info: CustomEnumType(val1, val2, val3)

    Namespace(p=<CustomEnumType.VAL1: 1>)
    Namespace(p=<CustomEnumType.VAL2: 2>)
    usage: issue25061.py [-h] [-p P]
    issue25061.py: error: argument -p: CustomEnumType: use one of
        {val1, val2, val3}

I was toying with writing a custom Action class that would create its own type and help attributes based on the enum parameter.  But since this EnumType.__repr__ takes care of the help angle, I don't think I'll bother.

If there's enough interest, I can imagine casting this EnumType as a formal patch, complete with tests and documentation.  Till then, feel free to experiment with and refine these ideas.
History
Date User Action Args
2015-09-14 20:56:17paul.j3setrecipients: + paul.j3, barry, desbma
2015-09-14 20:56:17paul.j3setmessageid: <1442264177.81.0.0770566960303.issue25061@psf.upfronthosting.co.za>
2015-09-14 20:56:17paul.j3linkissue25061 messages
2015-09-14 20:56:17paul.j3create