title: argparse augment sub-command defaults via global options
body: <p>I would like to be able to use the global options from an argparse.ArgumentParser object to override/augment the defaults values for a sub-command.</p>
  
  <p>An example would be that displayed help reflects the global updates, i.e., for the following toy example:</p>
  
  <pre><code>import argparse
  import os
  import sys
  
  # Global parser and options.
  parser = argparse.ArgumentParser(
      formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  
  parser.add_argument("--user", 
                      dest="user", 
                      default=os.environ.get("USER"),
                      help="Override the setting of the $USER variable.")
  
  # Sub-command parser and options.
  subparsers = parser.add_subparsers()
  
  command = subparsers.add_parser(
      "command",
      formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  
  command.add_argument("--config",
                       dest="config",
                       default="~%s/config" % os.environ.get("USER"),
                       help="The config file.")
  
  options = parser.parse_args()
  </code></pre>
  
  <p>Ideally when when I run this in help mode I would get, </p>
  
  <pre><code>&gt; python example.py --user thing command --help
  usage: example.py command [-h] [--config CONFIG]
  
  optional arguments:
    -h, --help       show this help message and exit
    --config CONFIG  The config file. (default: ~thing/config)
  </code></pre>
  
  <p>i.e., the config file path is user specific (thing). I realize that I could change the default config to be <code>"~%(user)s/config"</code> and then resolve this at run-time with the options namespace, however I would like the help to be more explicit.</p>
  
  <p>I gather an alternative solution would be to try to parse the arguments once to obtain the global options, i.e., </p>
  
  <pre><code>if "--help" in sys.argv:
  
      # Parse the command minus the help to obtain the global options. 
      args = sys.argv[1:]
      args.remove("--help")
  
      # Update the defaults with the global options.
      options = parser.parse_args(args) 
      command.set_defaults(config="~%s/config" % options.user)
  
      # Re-parse the options.
      parser.parse_args()
  </code></pre>
  
  <p>Though this seems somewhat hacky. Is there a better approach/solution?</p>