title: argparse - Combining parent parser, subparsers and default values
body: <p>I wanted to define different subparsers in a script, with both inheriting options from a common parent, but with different defaults. It doesn't work as expected, though.</p>
  
  <p>Here's what I did:</p>
  
  <pre><code>import argparse
  
  # this is the top level parser
  parser = argparse.ArgumentParser(description='bla bla')
  
  # this serves as a parent parser
  base_parser = argparse.ArgumentParser(add_help=False)
  base_parser.add_argument('-n', help='number', type=int)
  
  
  # subparsers
  subparsers = parser.add_subparsers()
  subparser1= subparsers.add_parser('a', help='subparser 1', 
                                     parents=[base_parser])
  subparser1.set_defaults(n=50)
  subparser2 = subparsers.add_parser('b', help='subparser 2',
                                     parents=[base_parser])
  subparser2.set_defaults(n=20)
  
  args = parser.parse_args()
  print args
  </code></pre>
  
  <p>When I run the script from the command line, this is what I get:</p>
  
  <pre><code>$ python subparse.py b
  Namespace(n=20)
  
  $ python subparse.py a
  Namespace(n=20)
  </code></pre>
  
  <p>Apparently, the second <code>set_defaults</code> overwrites the first one in the parent. Since there wasn't anything about it in the argparse documentation (which is pretty detailed), I thought this might be a bug. </p>
  
  <p>Is there some simple solution for this? I could check the <code>args</code> variable afterwards and replace <code>None</code> values with the intended defaults for each subparser, but that's what I expected argparse to do for me.</p>
  
  <p>This is Python 2.7, by the way.</p>