Difference between --default and -store_const in argparse

I read the following in argparse :

' store_const ' - Saves the value specified by the keyword const argument. (Note that the default keyword argument const is unhelpful None.) The store_const action is most often used with optional arguments that indicate some kind of flag. For example:

 >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', action='store_const', const=42) >>> parser.parse_args('--foo'.split()) Namespace(foo=42)` 

How does this differ from setting the default value for an argument with the default parameter?

+7
python arguments argparse
source share
1 answer

What did you get with parse_args(''.split()) ? I would expect foo=None .

Now add default='39' to the argument definition.

default is the value that the attribute receives when the argument is absent. const is the value that it receives when given. Also note that const is only allowed when the store_const action (and a few other special cases).

Notice what happens when I define the store_true action:

 In [30]: p.add_argument('--bar', action='store_true') Out[30]: _StoreTrueAction(option_strings=['--bar'], dest='bar', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None) 

The Action object that it creates has the attribute const=True and default=False . It also has nargs=0 . This is the store_const action with these special values.

[The user 'advanced' can experiment with add_argument('--foo', nargs='?', default='one', const='two') ].

+9
source share

All Articles