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