title: Python Argparse: Using a single tack as a flag, e.g. `./myscript -5` like Git and CoreUtils
body: <h1>Using single-tack <code>-</code> as a flag in Python Argparse</h1>
  <p>Many GNU CoreUtils (<code>head</code>, <code>tail</code>, etc) and Git have a command-line feature that allows one to do e.g.</p>
  <pre class="lang-sh prettyprint-override"><code>$ head -5 ...
  $ tail -20 ...
  $ git log -5 ...
  </code></pre>
  <p>How can I achieve the same effect by using Python's <code>argparse</code> module?</p>
  <h2>Example Parser</h2>
  <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3
  import argparse
  p = argparse.ArgumentParser()
  p.add_argument('-', dest='dash', help='Tell me how many!')
  p.add_argument('-n', dest='n', help='This works, but I dislike it!')
  p.add_argument('positional', nargs='*')
  print(p.parse_intermixed_args())
  </code></pre>
  <p>This generates the usagee:</p>
  <pre class="lang-sh prettyprint-override"><code>$ ./example.py --help
  usage: example.py [-h] [- DASH] [-n N] [positional [positional ...]]
  </code></pre>
  <h2>What works</h2>
  <p>Using e.g. <code>-n5</code>, <code>-n=5</code>, and <code>-n 5</code> all work as expected.</p>
  <pre class="lang-sh prettyprint-override"><code>$ ./example.py before -n5 after
  Namespace(dash=None, n='5', positional=['before', 'after'])
  
  $ ./example.py before -n=5 after
  Namespace(dash=None, n='5', positional=['before', 'after'])
  
  $ ./example.py before -n 5 after
  Namespace(dash=None, n='5', positional=['before', 'after'])
  </code></pre>
  <h2>What Does Not Work As Expected</h2>
  <p>Here, we can see that <code>-5</code> does not work as expected.  Surprisingly, <code>- 5</code> does work.</p>
  <p><strong>This first example below is my desired usage, but the result is not what I want.</strong></p>
  <pre class="lang-sh prettyprint-override"><code># This does not work, `-5` is considered a positional argument.
  # ~~ THIS IS WHAAT I WANT TO HAVE WORK! ~~
  $ ./example.py before -5 after
  Namespace(dash=None, n=None, positional=['before', '-5', 'after'])
  
  # This works, but is not what I want
  $ ./example.py before - 5 after
  Namespace(dash='5', n=None, positional=['before', 'after'])
  </code></pre>