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.:

Copyparser.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).

Copyrating = 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)
🌐
Python documentation
docs.python.org › 3 › howto › argparse.html
Argparse Tutorial — Python 3.14.3 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)
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
Python argparse , add_argument, type = <some function> rather than int? - Stack Overflow
In a project I see the following use of add_argument(): parser = argparse.ArgumentParser() parser.add_argument("--somearg",type=make_arg_instance,help='blahblahblah') args = parser.parse_args() i ... More on stackoverflow.com
🌐 stackoverflow.com
Argparse, type hint
What should be the type hint when I pass an argparse argument to a function in Python? More on discuss.python.org
🌐 discuss.python.org
0
0
July 17, 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
🌐
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?

🌐
Micahrl
me.micahrl.com › blog › python-argparse-custom-actions-types
Python, argparse, and custom actions and types
This works, but it feels wrong, and easy to forget, and I wanted something that worked like the type= parameter that can be passed to add_argument. As it turns out, you can write a custom action that does this modification at argument parsing time. Here’s what I ended up with (combined with my resolvepath() function listed above): class StorePathAction(argparse.Action): """Resolve paths during argument parsing""" def __call__(self, parser, namespace, values, option_string=None): if type(values) is list: paths = [resolvepath(v) for v in values] else: paths = resolvepath(values) setattr(namespace, self.dest, paths) def main(*args, **kwargs): # ...
🌐
Real Python
realpython.com › command-line-interfaces-python-argparse
Build Command-Line Interfaces With Python's argparse – Real Python
December 14, 2024 - To do this, you can use the type argument of .add_argument(). As an example, say that you want to write a sample CLI app for dividing two numbers. The app will take two options, --dividend and --divisor. These options will only accept integer numbers at the command line: ... import argparse parser = argparse.ArgumentParser() parser.add_argument("--dividend", type=int) parser.add_argument("--divisor", type=int) args = parser.parse_args() print(args.dividend / args.divisor)
🌐
Python Module of the Week
pymotw.com › 2 › argparse
argparse – Command line option and argument parsing. - Python Module of the Week
argparse treats all argument values as strings, unless you tell it to convert the string to another type.
Find elsewhere
🌐
Andrey-zherikov
andrey-zherikov.github.io › argparse › supported-types.html
Supported types | argparse documentation
argparse supports the following strings as a <value> (comparison is case-insensitive): Numeric (according to std.traits.isNumeric) and string (according to std.traits.isSomeString) data types are seamlessly converted to destination type using std.conv.to:
🌐
Mimo
mimo.org › glossary › python › argparse
Python argparse: Syntax, Usage, and Examples
The Python argparse module gives you a powerful, built-in solution for building command-line interfaces. With just a few lines, you can define positional and optional arguments, handle boolean flags, enforce types, supply default values, and even accept lists.
🌐
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 ...
      » pip install typed-argparse
    
Published   Sep 30, 2022
Version   0.2.4
🌐
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
Common built-in types and functions can be used directly as the value of the type argument: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('foo', type=int) >>> parser.add_argument('bar', type=file) >>> parser.parse_args('2 temp.txt'.split()) Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
🌐
Medium
medium.com › @tushar_aggarwal › easy-argparse-a-guide-to-handling-command-line-arguments-9cdf62ff46db
Easy argparse: A guide to handling command-line arguments | by Tushar Aggarwal | Medium
July 3, 2023 - By default, argparse treats all command-line arguments as strings. However, you can specify the type of argument using the type parameter.
🌐
CRAN
cran.r-project.org › web › packages › argparse › vignettes › argparse.html
argparse Command Line Argument Parsing
argparse is a command line argument parser inspired by Python’s “argparse” library.
🌐
Python.org
discuss.python.org › python help
Argparse, type hint - Python Help - Discussions on Python.org
July 17, 2023 - What should be the type hint when I pass an argparse argument to a function in Python?
🌐
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)?

🌐
Python Module of the Week
pymotw.com › 3 › argparse › index.html
argparse — Command-Line Option and Argument Parsing
December 30, 2016 - argparse treats all argument values as strings, unless it is told to convert the string to another type.
🌐
Stackify
stackify.com › python-argparse-definition-how-to-use-and-best-practices
Python argparse: Definition, How to Use, and Best Practices - Stackify
February 4, 2025 - Python argparse provides several features to make building CLIs easier: positional arguments: requires users to provide mandatory inputs in a specific order · optional arguments:allows users to specify flexible inputs, such as flags (–verbose) or key-value pairs (–timeout 10) type validation: automatically checks if inputs are of the expected type (e.g., integers, floats, or strings)
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-argparse-to-write-command-line-programs-in-python
How To Use argparse to Write Command-Line Programs in Python | DigitalOcean
March 11, 2021 - In this tutorial, you’ll use some of the utilities exposed by Python’s argparse standard library module. You’ll write command-line interfaces that accept positional and optional arguments to control the underlying program’s behavior.
🌐
Erlang
erlang.org › doc › apps › stdlib › argparse.html
argparse — stdlib v7.2.1
help - Specifies help/usage text for the argument. argparse provides automatic generation based on the argument name, type and default value, but for better usability it is recommended to have a proper description.