Skip to content
Advertisement

In Python argparse, is it possible to have paired –no-something/–something arguments?

I’m writing a program in which I would like to have arguments like this:

JavaScript

Is there a way to get argparse to do this for me?

Advertisement

Answer

v3.9 has added an action class that does this. From the docs (near the end of the action section)

The BooleanOptionalAction is available in argparse and adds support for boolean actions such as --foo and --no-foo:

JavaScript

To explore @wim’s comment about not being mutually_exclusive.

JavaScript

The last line shows that the add_argument created a BooleanOptionalAction Action class.

With various inputs:

JavaScript

So you can supply both flags, with the last taking effect, over writing anything produced by the previous. It’s as though we defined two Actions, with the same dest, but different True/False const.

The key is that it defined two flag strings:

JavaScript

Part of the code for this new class:

JavaScript

So the action __init__ defines the two flags, and the __call__ checks for the no part.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement