@@ -841,6 +841,53 @@ translated messages.
841
841
842
842
To translate your own strings in the :mod: `argparse ` output, use :mod: `gettext `.
843
843
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
+
844
891
Conclusion
845
892
==========
846
893
0 commit comments