Message322233
The 'choices' mechanism is a simple 'value in choices' test. A dictionary (or other mapping) works because it works with 'in'.
'type' as noted is the means that argparse provides for transforming an input string into some other object (most commonly a number with 'int' or 'float'). The choices test is performed after the type transformation.
The 'set_defaults()' with subparsers is offered almost as a parenthetical idea, and has nothing to do with 'choices' or 'type'. 'set_defaults' is just another way of setting default values, and works even with 'dest' which aren't otherwise defined. If that isn't clear, I'd suggest testing it with the main parser.
In Python functions are first class objects, and thus can be used just like strings or numbers - assigned to variables, put in lists, etc.
In:
adict = {'I':int, 'F':float}
parser.add_argument('foo', type=lambda x: adict.get(x), choices=adict.values())
the 'type' transforms the commandline string into a the dictionary value, and 'choices' then tests that against the values of the dictionary. (I had to use `lambda` instead of 'adict.get' directly because of testing that 'type' does.) |
|
Date |
User |
Action |
Args |
2018-07-23 16:46:22 | paul.j3 | set | recipients:
+ paul.j3, rhettinger, bethard, zach.ware, porton |
2018-07-23 16:46:22 | paul.j3 | set | messageid: <1532364382.53.0.56676864532.issue34188@psf.upfronthosting.co.za> |
2018-07-23 16:46:22 | paul.j3 | link | issue34188 messages |
2018-07-23 16:46:22 | paul.j3 | create | |
|