Argparse optional argument with different default if specified without a value


Consider three different runs of a program:

python3 prog.py python3 prog.py --x python3 prog.py --x 2

Is it possible to use argparse such that, for example, in the first case, x==None, in the second case, x==1, and in the third, x==2?


nargs'?' with a const parameter handles this 3-way input nicely..

In [2]: parser = argparse.ArgumentParser() In [3]: parser.add_argument('-x','--x', nargs='?', type=int, const=1) ... In [4]: parser.parse_args([]) Out[4]: Namespace(x=None) In [5]: parser.parse_args(['-x']) Out[5]: Namespace(x=1) In [6]: parser.parse_args(['-x','2']) Out[6]: Namespace(x=2)

I could have also given it a default parameter.

<a href="https://stackoverflow.com/questions/44745588/how-to-add-multiple-argument-options-in-python-using-argparse" rel="nofollow">how to add multiple argument options in python using argparse?</a>


If you are happy to do a little post-processing, you can get it:

sentinel = object() parser.add_argument('--x', nargs='?', type=int, default=sentinel) args = parser.parse_args() if args.x is sentinel: args.x = None elif args.x is None: args.x = 1

However, it is bending the tool in a bit of a strange way. You may want to consider instead the <a href="https://docs.python.org/3/library/argparse.html#action" rel="nofollow">count</a> action, which is commonly used to specify verbosity levels, for example (-v, -vv, -vvv).


  • Getting intersection of two lists in python
  • Arguments that are dependent on other arguments with Argparse
  • Run command line containing multiple strings from python script
  • Simple command line application in python - parse user input?
  • Passing parameters to Python subprocess.Popen
  • SyntaxError trying to execute python 3 code with python 2.7
  • Support arbitrary number of related named arguments with Python argparse
  • how to pull out text from a div class using selenium headless [closed]
  • Python argparse AssertionError from metavar `[[USER@]HOST:]FILE`
  • python argparse default value for optional argument
  • Copying files and creating new folders based on “creationdate”
  • Can I run Robotium tests automatically in parallel on multiple emulators?
  • Android : Strike out Text with bold or thicker line than default STRIKE_THRU_TEXT_FLAG
  • Swift gives “self used before all stored procedures are initialized” error when building child nodes
  • How to add System.Windows dll to Visual Studio 2010 express?
  • Difference between two forms of Perl filename wildcard command
  • Jquery resizable reposition handle after scroll
  • C++ Coin flip program error
  • string.IsNullOrEmpty() Doesn't Seem to Work on a String within a Class within a Class
  • Is there a way to link a linux's thread TID and a pthread_t “thread ID”
  • end daemon processes with multiprocessing module
  • 'doc_del_count' bigger than 'doc_count' on CouchDB
  • Regex for Specific Tag
  • Is it possible to run clang with llc flags
  • WPF Template Binding in ToggleButton UserControl
  • Adding elements to a huge XML file
  • How integrated is Collada to OpenGL ES
  • Jackson Parser: ignore deserializing for type mismatch
  • FFmpeg Conversion Error
  • Paperclip, set path outside of rails root folder
  • Java Scanner input dilemma. Automatically inputs without allowing user to type
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • Spray.io: When (not) to use non-blocking route handling?
  • Modifying destination and filename of gulp-svg-sprite
  • what is the difference between the asp.net mvc application and asp.net web application
  • How do you troubleshoot character encoding problems?
  • GridView Sorting works once only
  • Matrix multiplication with MKL
  • Checking variable from a different class in C#
  • Binding checkboxes to object values in AngularJs