简体   繁体   中英

What's the point of having both action='store_true' and default=False in parser.add_argument?

I have always read codes like this,

parser.add_argument('--name', action='store_true', default=False, help='XXX')

For example, this code man-sf-emnlp/train.py - midas-research

But what is the point of setting default=False when you already set action='store_true' ?

There's no point. From the docs :

'store_true' and 'store_false' - These are special cases of 'store_const' used for storing the values True and False respectively. In addition, they create default values of False and True respectively.

(added bold)


In the comments, Charles Duffy said, "It's a stylistic choice to be explicit rather than implicit", which is a fair point, but it also means that if you're editing the code and accidentally mismatch the action and default , it'll break:

>>> parser.add_argument('--name', action='store_true', default=True)
>>> parser.parse_args(['--name'])  # Good
Namespace(name=True)
>>> parser.parse_args([])  # Bad
Namespace(name=True)

And I think the implicit default is obvious anyway.

The __init__ for the store_true subclass is:

class _StoreTrueAction(_StoreConstAction):

    def __init__(self,
                 option_strings,
                 dest,
                 default=False,
                 required=False,
                 help=None):
        super(_StoreTrueAction, self).__init__(
            option_strings=option_strings,
            dest=dest,
            const=True,
            default=default,
            required=required,
            help=help)

Notice that it sets default=False . The user code can override that, but what's the point? This subclass is just a store_const where the default is False and the const is True .

add_argument takes a number of keyword parameters and creates an Action subclass object. Different actions make use of different combinations of parameters. add_argument takes a casual approach to required or superfluous parameters. That is, there isn't a lot of code that checks that just the right parameters have been defined.

I'd leave it off since the default is the correct one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM