paul j3 added the comment:
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.
----------
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue25061>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com