[docs] [issue16399] argparse: append action with default list adds to list instead of overriding

SylvainDe report at bugs.python.org
Thu Jun 19 13:23:07 CEST 2014


SylvainDe added the comment:

As this is likely not to get solved, is there a recommanded way to work around this issue ?

Here's what I have done :

  import argparse
  def main():
      """Main function"""
      parser = argparse.ArgumentParser()
      parser.add_argument('--foo', action='append')
      for arg_str in ['--foo 1 --foo 2', '']:
          args = parser.parse_args(arg_str.split())
          if not args.foo:
              args.foo = ['default', 'value']
          print(args)

printing

  Namespace(foo=['1', '2'])
  Namespace(foo=['default', 'value'])

as expected but I wanted to know if there a more argparse-y way to do this. I have tried using `set_defaults` without any success.

Also, as pointed out the doc for optparse describes the behavior in a simple way : "The append action calls the append method on the current value of the option. This means that any default value specified must have an append method. It also means that if the default value is non-empty, the default elements will be present in the parsed value for the option, with any values from the command line appended after those default values".

----------
nosy: +SylvainDe

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


More information about the docs mailing list