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 bethard, paul.j3, porton, rhettinger, zach.ware
Date 2018-07-23.16:46:22
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1532364382.53.0.56676864532.issue34188@psf.upfronthosting.co.za>
In-reply-to
Content
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.)
History
Date User Action Args
2018-07-23 16:46:22paul.j3setrecipients: + paul.j3, rhettinger, bethard, zach.ware, porton
2018-07-23 16:46:22paul.j3setmessageid: <1532364382.53.0.56676864532.issue34188@psf.upfronthosting.co.za>
2018-07-23 16:46:22paul.j3linkissue34188 messages
2018-07-23 16:46:22paul.j3create