Argparse: How to disallow some options in the presence of others - Python
<p>I have the following utility:</p>

<pre><code>import argparse

parser = argparse.ArgumentParser(description='Do some action.')
parser.add_argument('--foo', '--fo', type=int, default=-1, help='do something foo')
parser.add_argument('--bar', '--br', type=int, default=-1, help='do something bar')
parser.add_argument('--baz', '--bz', type=int, default=-1, help='do something baz')
parser.add_argument('--bat', '--bt', type=int, default=-1, help='do something bat')
</code></pre>

<p>However, if the <code>--foo</code> option is used, the <code>--bat</code> option should be disallowed, and conversely, the <code>--bat</code> option should only be used if <code>--bar</code> and <code>--baz</code> are present. How can I accomplish that using <code>argparse</code>? Sure, I could add a bunch of <code>if / else</code> blocks to check for that, but there's something built-in <code>argparse</code> that could do that for me? </p>

<p>You can create mutually-exclusive groups of options with <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow"><code>parser.add_mutually_exclusive_group</code></a>:</p>

<pre><code>group = parser.add_mutually_exclusive_group()
group.add_argument('--foo', '--fo', type=int, default=-1, help='do something foo')
group.add_argument('--bat', '--bt', type=int, default=-1, help='do something bat')
</code></pre>

<p>, but for more complex dependency graphs (for example, <code>--bat</code> requiring <code>--bar</code> and <code>--baz</code>), <code>argparse</code> doesn't offer any specific support. That'd be going too far in the direction of the <a href="https://en.wikipedia.org/wiki/Inner-platform_effect" rel="nofollow">inner-platform effect</a>, trying to rebuild too much of the full generality of a complete programming language within the <code>argparse</code> subsystem.</p>

python parsing command-line argparse