summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSavannah Ostrowski <savannahostrowski@gmail.com>2024-10-17 11:41:22 (GMT)
committerGitHub <noreply@github.com>2024-10-17 11:41:22 (GMT)
commitdbcc5ac4709dfd8dfaf323d51f135f2218d14068 (patch)
tree15a927cdb97c437d76b2ec9f1576689b8d0fe119
parent7b04496e5c7ed47e9653f4591674fc9ffef34587 (diff)
downloadcpython-dbcc5ac4709dfd8dfaf323d51f135f2218d14068.zip
cpython-dbcc5ac4709dfd8dfaf323d51f135f2218d14068.tar.gz
cpython-dbcc5ac4709dfd8dfaf323d51f135f2218d14068.tar.bz2
gh-95836: Add custom type converter examples to argparse tutorial (GH-125376)
-rw-r--r--Doc/howto/argparse.rst47
1 files changed, 47 insertions, 0 deletions
diff --git a/Doc/howto/argparse.rst b/Doc/howto/argparse.rst
index 30d9ac7..1efbee6 100644
--- a/Doc/howto/argparse.rst
+++ b/Doc/howto/argparse.rst
@@ -841,6 +841,53 @@ translated messages.
To translate your own strings in the :mod:`argparse` output, use :mod:`gettext`.
+Custom type converters
+======================
+
+The :mod:`argparse` module allows you to specify custom type converters for
+your command-line arguments. This allows you to modify user input before it's
+stored in the :class:`argparse.Namespace`. This can be useful when you need to
+pre-process the input before it is used in your program.
+
+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)
+
+Output:
+
+.. code-block:: shell-session
+
+ $ python prog.py -a value1 +a value2
+ Namespace(a=[('-', 'value1'), ('+', 'value2')])
+
+In this example, we:
+
+* Created a parser with custom prefix characters using the ``prefix_chars``
+ parameter.
+
+* Defined two arguments, ``-a`` and ``+a``, which used the ``type`` parameter to
+ create custom type converters to store the value in a tuple with the prefix.
+
+Without the custom type converters, the arguments would have treated the ``-a``
+and ``+a`` as the same argument, which would have been undesirable. By using custom
+type converters, we were able to differentiate between the two arguments.
+
Conclusion
==========