[issue24956] Default value for an argument that is not in the choices list gets accepted

paul j3 report at bugs.python.org
Fri Sep 4 22:53:20 CEST 2015


paul j3 added the comment:

A related issue which Sworddragon found just before starting this issue is

    http://bugs.python.org/issue9625

The handling of defaults in argparse is a bit complicated.  In general it errs on the side of giving the user/developer freedom to set them how ever they want.  That's especially true in the case of non-string defaults.  A default does not have to be something that the user could give.  In particular the default 'default' is None, which can't be parsed from the command line.  The same for boolean values (the default 'type' does not translate string 'False' to boolean 'False'.)

Errors in the defaults are usually caught during program development.  

If the calling code generates the defaults dynamically, it seems reasonable that it should also check that they are valid.  The validity test for choices is a simple 'in' (contains) one.  'choices' can be a list or dictionary (keys), and can even be dynamically generated.

     parser = ....
     choices = <get a list>
     default = <get a value>
     if default not in choices:
         <scream>
     parser.add_argument(..., choices=choices, default=default)
     etc.

----------
nosy: +paul.j3

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24956>
_______________________________________


More information about the Python-bugs-list mailing list