Skip to content

Commit 253d69f

Browse files
[3.13] gh-95836: Add custom type converter examples to argparse tutorial (GH-125376) (GH-125643)
(cherry picked from commit dbcc5ac) Co-authored-by: Savannah Ostrowski <[email protected]>
1 parent 06dc0bc commit 253d69f

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Doc/howto/argparse.rst

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -841,6 +841,53 @@ translated messages.
841841

842842
To translate your own strings in the :mod:`argparse` output, use :mod:`gettext`.
843843

844+
Custom type converters
845+
======================
846+
847+
The :mod:`argparse` module allows you to specify custom type converters for
848+
your command-line arguments. This allows you to modify user input before it's
849+
stored in the :class:`argparse.Namespace`. This can be useful when you need to
850+
pre-process the input before it is used in your program.
851+
852+
When using a custom type converter, you can use any callable that takes a
853+
single string argument (the argument value) and returns the converted value.
854+
However, if you need to handle more complex scenarios, you can use a custom
855+
action class with the **action** parameter instead.
856+
857+
For example, let's say you want to handle arguments with different prefixes and
858+
process them accordingly::
859+
860+
import argparse
861+
862+
parser = argparse.ArgumentParser(prefix_chars='-+')
863+
864+
parser.add_argument('-a', metavar='<value>', action='append',
865+
type=lambda x: ('-', x))
866+
parser.add_argument('+a', metavar='<value>', action='append',
867+
type=lambda x: ('+', x))
868+
869+
args = parser.parse_args()
870+
print(args)
871+
872+
Output:
873+
874+
.. code-block:: shell-session
875+
876+
$ python prog.py -a value1 +a value2
877+
Namespace(a=[('-', 'value1'), ('+', 'value2')])
878+
879+
In this example, we:
880+
881+
* Created a parser with custom prefix characters using the ``prefix_chars``
882+
parameter.
883+
884+
* Defined two arguments, ``-a`` and ``+a``, which used the ``type`` parameter to
885+
create custom type converters to store the value in a tuple with the prefix.
886+
887+
Without the custom type converters, the arguments would have treated the ``-a``
888+
and ``+a`` as the same argument, which would have been undesirable. By using custom
889+
type converters, we were able to differentiate between the two arguments.
890+
844891
Conclusion
845892
==========
846893

0 commit comments

Comments
 (0)