I can't seem to find any support for multiple arguments of different types. All I could find is this issue request (https://bugs.python.org/issue38217).

Here it was recommended to do a type check in the 'post parsing' code, e.g. have both 5 and fileName be strings, and simply convert the 5 to an int as required. You could specify the argument simply as such, by taking exactly 2 arguments.:

parser.add_argument('--rating',
                    nargs=2,
                    type=str,
                    help="1st arg: rating (1-5), 2nd arg: file name.")

Then, you can unpack the values from the list (as nargs will bundle values into a list).

rating = int(args.rating[0])
file_name = args.rating[1]

Hope this helps!

Answer from You_Donut on Stack Overflow
🌐
Python
docs.python.org › 3 › library › argparse.html
argparse — Parser for command-line options, arguments and subcommands
The bool() function is not recommended as a type converter. All it does is convert empty strings to False and non-empty strings to True. This is usually not what is desired: >>> parser = argparse.ArgumentParser() >>> _ = parser.add_argument('--verbose', type=bool) >>> parser.parse_args(['--verbose', 'False']) Namespace(verbose=True)
Discussions

argparse: type vs action
I always thought types were custom actions. And when I look at the API doc, it says there is a fixed set of seven valid actions — no custom ones possible, apparently. But then, further down the page, it tells you exactly how to write a custom action. Yeah, I'm pretty confused too. More on reddit.com
🌐 r/learnpython
8
2
January 10, 2023
Suggestions for retaining type hinting when using argparse without telling my IDE to look the other way
So this post is one of the very top hits on Google (at least for me) when I searched for "argparse type hinting"... Just thought I would say that I think OP's solution is still the current best practice, at least that I'm aware of, without bringing in anything outside the Python standard library. There is now a version of argparse called typed-argparse which, as the name implies, is just argparse but with typing. However, you have to load it from PyPi and I will only do that if I have absolutely no other choice. The empty class definition that OP suggests works great for making VSCode and PyCharm autocomplete work, and IMO that's a completely legitimate reason for it ­— if it helps you write better code and not do dumb stuff, it's a good thing. More on reddit.com
🌐 r/learnpython
5
9
December 12, 2021
command line interface - Adding options with different argument types using Python's argparse module - Stack Overflow
I'm trying to add a command-line option that takes three arguments, where the last two must be integers. $ myapp --opt str_value 2 4 First I tried something like this. parser.add_argument( '--... More on stackoverflow.com
🌐 stackoverflow.com
python - Can one commandline argument's `type` be dependent on the value of another argument with argparse? - Stack Overflow
I'm writing a collection of python scripts that can parse multiple input formats, but the type of these inputs is decided by another commandline argument. How can I make one argument affect the type of another argument? ... import argparse def load_single_file(filepath: str): ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.4 documentation
When using a custom type converter, you can use any callable that takes a single string argument (the argument value) and returns the converted value. However, if you need to handle more complex scenarios, you can use a custom action class with the action parameter instead. For example, let’s say you want to handle arguments with different prefixes and process them accordingly: import argparse parser = argparse.ArgumentParser(prefix_chars='-+') parser.add_argument('-a', metavar='<value>', action='append', type=lambda x: ('-', x)) parser.add_argument('+a', metavar='<value>', action='append', type=lambda x: ('+', x)) args = parser.parse_args() print(args)
🌐
Reddit
reddit.com › r/learnpython › argparse: type vs action
r/learnpython on Reddit: argparse: type vs action
January 10, 2023 -

I have just started learning Python, coming from more low level language's but have some shell scripting experiences.

I wanted to write a tool with command line arguments, and quickly found the argparse module in Python's documentation. I am prone to object oriented programming and quickly ended up in a situation with a mess of post-processing string arguments into different class instances.

My mediocre Google-Fu found multiple ways of cleanly support custom type parsing, namely using the add_argument's type or action parameters. However, no site really explained their purposes; just a bunch of examples, using either mechanism. I did not feel I got a good understanding from the docs either.

What is the purpose of these two mechanics?

I read somewhere that arguments are passed through the callable type parameter and then forwarded to the callable action parameter.

Is the type mechanism supposed to parse a string to another type, and action supposed to use that newly created type instance to do whatever magic you want to happen?

🌐
Mimo
mimo.org › glossary › python › argparse
Python argparse: Syntax, Usage, and Examples
If a user enters an invalid type, argparse shows a helpful error message automatically. You can also handle float values, files, or even custom validation functions. Use the default parameter to specify fallback values if the user omits the argument: ... If --timeout isn't supplied, args.timeout will default to 30. This makes it easy to configure sane defaults without requiring the user to input everything manually. The concept of a Python argparse default value is common in configuration-heavy applications like deployment scripts or test automation tools.
🌐
Micahrl
me.micahrl.com › blog › python-argparse-custom-actions-types
Python, argparse, and custom actions and types
What I’ve done is a simple ... string). argparse has support for some basic types like dates and numbers built in, but this lets you add support for any number of custom classes whenever you like.
Find elsewhere
🌐
Read the Docs
python.readthedocs.io › fr › latest › library › argparse.html
16.4. argparse — Parser for command-line options, arguments and sub-commands — documentation Python 3.7.0a0
To ease the use of various types of files, the argparse module provides the factory FileType which takes the mode=, bufsize=, encoding= and errors= arguments of the open() function.
🌐
PyPI
pypi.org › project › typed-argparse › 0.2.4
typed-argparse · PyPI
Support for common types (Optional, List, Literal, Enum, Union, and regular classes) Convenience functionality to map Literal/Enum to choices · Convenience functionality to map Union to subcommands ... The only requirement is a modern Python (3.6+). import argparse import sys from typing import List, Optional from typed_argparse import TypedArgs # Step 1: Add an argument type.
      » pip install typed-argparse
    
Published   Sep 30, 2022
Version   0.2.4
🌐
Medium
baoshangu.medium.com › python-argparse-custom-action-and-custom-type-8c8fa1e8ccb8
Python argparse custom action and custom type | by Baoshan Gu | Medium
June 18, 2021 - The pattern is an additional argument passed to the custom type. import os import reclass PatternedName(object): def __init__(self, pattern): self._pattern = pattern def __call__(self, name): if re.match(self._pattern, name): return name else: raise argparse.ArgumentTypeError(f"{name} does not follow the expected pattern.")parser = argparse.ArgumentParser(description="Custom type example") parser.add_argument('--patterned_name', type=PatternedName(r'^[a-f0-9]+$')) args = parser.parse_args()
🌐
Reddit
reddit.com › r/learnpython › suggestions for retaining type hinting when using argparse without telling my ide to look the other way
r/learnpython on Reddit: Suggestions for retaining type hinting when using argparse without telling my IDE to look the other way
December 12, 2021 -

So let's say we would like to make our program to have a command-line interface. By default, parsed arguments coming from the parse_args() method in the argparse module has a Namespace typing. Which doesn't help with auto-completion nor with type hinting argument types.

Alright, so I type hint the exact namespace that I expect:

 import argparse

class MyProgramArgs(argparse.Namespace):
    somearg: str
    somenum: int

def process_argv():
    parser = argparse.ArgumentParser()
    parser.add_argument('--somearg', default='defaultval')
    parser.add_argument('--somenum', type=int)
    parsed: MyProgramArgs = parser.parse_args()  # type: ignore
    the_arg = parsed.somearg

And for all purposes, this works. I get auto-completion suggestion and appropriate typing hinting. But I had to explicitly tell my code editor to look the other way in this line:

 parsed: MyProgramArgs = parser.parse_args()  # type: ignore

Could the same outcome have been managed without this hack (and without using 3rd party libraries)?

🌐
PyPI
pypi.org › project › typed-argparse › 0.2.1
typed-argparse
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Real Python
realpython.com › ref › stdlib › argparse
argparse | Python Standard Library – Real Python
The Python argparse module is a framework for creating user-friendly command-line interfaces (CLI). It allows you to define command-line arguments and options. It takes care of parsing them, and automatically generates help and usage messages ...
🌐
DEV Community
dev.to › usooldatascience › mastering-pythons-argparse-a-comprehensive-guide-for-beginners-48fn
Mastering Python’s argparse: A Comprehensive Guide for Beginners - DEV Community
September 15, 2024 - The argparse module provides a simple way to handle command-line arguments passed to your Python script. It automatically generates help messages, handles type checking, and can process both optional and positional arguments.
Top answer
1 of 3
3

From the docs:

Different values of nargs may cause the metavar to be used multiple times. Providing a tuple to metavar specifies a different display for each of the arguments:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', nargs=2)
>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
>>> parser.print_help()
usage: PROG [-h] [-x X X] [--foo bar baz]

options:
 -h, --help     show this help message and exit
 -x X X
 --foo bar baz

So specify metavar=('<str>', '<int>', '<int>').

2 of 3
2

As others wrote, giving a tuple metavar that matches the nargs gives the desired usage/help display:

In [20]: parser=argparse.ArgumentParser();
    ...: parser.add_argument(
    ...:     '--opt',
    ...:     nargs=3,
    ...:     metavar=('<str>', '<int>', '<int>'),
    ...:     help="...",
    ...: );

In [21]: parser.print_help()
usage: ipykernel_launcher.py [-h] [--opt <str> <int> <int>]

options:
  -h, --help            show this help message and exit
  --opt <str> <int> <int>
                        ...

In [22]: parser.parse_args('--opt foo 2 3'.split())
Out[22]: Namespace(opt=['foo', '2', '3'])

An alternative would let it display as '--opt OPT OPT OPT' and give more details in the help string.

parents is just a way of copying the add_argument of one parser to a new one. It does not add any functionality.

The other task is testing and converting those three strings.

The type function only sees one argument string at a time, so can't (readily) distinguish between the string and int arguments.

The action __call__ method does get all (3) strings. So a custom Action class could test and convert the 2nd and 3rd, before saving them to the namespace. The code to do this would look a lot like the code you'd write to process args.opt after parsing. You'll have to look at the argparse.py code to copy and modify a existing Action subclass.

But I think a custom 'Action' class is worth the work only if you have several arguments with this type of input. Otherwise, doing the post-argparse processing will be simplest.

You don't get extra credit for doing all the input handling within the parser.

In [27]: args=parser.parse_args('--opt foo bar 3'.split())
In [29]: try:
    ...:     opts = [args.opt[0], int(args.opt[1]), int(args.opt[2])]
    ...: except ValueError:
    ...:     parser.error('opt arguments should be str,int,int')
    ...:     
usage: ipykernel_launcher.py [-h] [--opt <str> <int> <int>]
ipykernel_launcher.py: error: opt arguments should be str,int,int
....
🌐
Stack Overflow
stackoverflow.com › questions › 67015478 › can-one-commandline-arguments-type-be-dependent-on-the-value-of-another-argum
python - Can one commandline argument's `type` be dependent on the value of another argument with argparse? - Stack Overflow
Anyways, type is called with just one argument, a string. It does not have access to anything else that is going on inside the parser at that time, not even the args namespace. The underlying philosophy of argparse is to parse arguments in the order that the user provides.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-pass-a-list-as-a-command-line-argument-with-argparse
How to pass a list as a command-line argument with argparse? - GeeksforGeeks
April 28, 2025 - You can do this by adding the following line at the beginning of your Python script: ... Add the argument to the argument parser using the add_argument() method. Use the type parameter to specify the data type of the argument, The list can be ...
🌐
Read the Docs
stackless.readthedocs.io › en › 2.7-slp › library › argparse.html
15.4. argparse — Parser for command-line options, arguments and sub-commands — Stackless-Python 2.7.15 documentation
Replace strings with implicit arguments such as �fault or %prog with the standard Python syntax to use dictionaries to format strings, that is, %(default)s and %(prog)s. Replace the OptionParser constructor version argument with a call to parser.add_argument('--version', action='version', version='<the version>'). 15.4. argparse — Parser for command-line options, arguments and sub-commands
🌐
YouTube
youtube.com › programmingknowledge
Python argparse and command line arguments - YouTube
In this Python Programming Tutorial for Beginners video I am going to show you How to use argparse to parse python scripts parameters.So basically we will d...
Published   June 27, 2020
Views   10K
🌐
GitHub
github.com › simon-ging › typedparser
GitHub - simon-ging/typedparser: Extension for python argparse with typehints and typechecks.
Create commandline arguments with type hints and checks while staying close to the syntax of the standard library's argparse. Utilities for typechecking and converting nested objects: Nested checking and conversion of python standard types
Author   simon-ging