Skip to content
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 20 additions & 31 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -801,7 +801,8 @@ Only actions that consume command-line arguments (e.g. ``'store'``,

The recommended way to create a custom action is to extend :class:`Action`,
overriding the :meth:`!__call__` method and optionally the :meth:`!__init__` and
:meth:`!format_usage` methods.
:meth:`!format_usage` methods. You can also register custom actions using the
:meth:`~ArgumentParser.register` method and reference them by their registered name.

An example of a custom action::

Expand Down Expand Up @@ -1023,7 +1024,9 @@ is only applied if the default is a string.
The argument to ``type`` can be any callable that accepts a single string.
If the function raises :exc:`ArgumentTypeError`, :exc:`TypeError`, or
:exc:`ValueError`, the exception is caught and a nicely formatted error
message is displayed. No other exception types are handled.
message is displayed. Other exception types are not handled. You can also
customize how the type is displayed in error messages by registering it with
the parser using :meth:`~ArgumentParser.register`.

Common built-in types and functions can be used as type converters:

Expand Down Expand Up @@ -2162,46 +2165,32 @@ Intermixed parsing

.. versionadded:: 3.7


Registering custom types or actions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. method:: ArgumentParser.register(registry_name, value, object)

It is possible to register custom actions, types, or other objects with
a parser using :meth:`!register`. This method is called when the action is
added to the parser. :meth:`!register` takes in the following arguments:

* *registry_name* - the name of the internal registry where the object
will be stored (e.g. ``action``, ``type``).

* *value* - the key under which the object will be registered.
Sometimes it's desirable to use a custom string in error messages to provide
more user-friendly output. In these cases, :meth:`!register` can be used to
register custom actions or types with a parser and allow you to reference the
type by their registered name instead of their callable name.

* *object* - the callable object to be registered.
The :meth:`!register` method accepts three arguments - a *registry_name*,
specifying the internal registry where the object will be stored (e.g.,
``action``, ``type``), *value*, which is the key under which the object will
be registered, and object, the callable to be registered.

The following example shows how to register a custom type with a parser::

>>> import argparse
>>> import enum
>>> class WinterMonths(enum.StrEnum):
... JAN = 'January'
... FEB = 'February'
... DEC = 'December'
...
>>> WinterMonths.__name__ = 'Winter Month'
>>> parser = argparse.ArgumentParser()
>>> parser.register('type', 'Winter Month', WinterMonths)
>>> parser.add_argument('--month', type=WinterMonths, action='store')
_StoreAction(option_strings=['--month'], dest='month', nargs=None, const=None, default=None, type=<enum 'Winter Month'>, choices=None, required=False, help=None, metavar=None, deprecated=False)
>>> parser.parse_args(['--month','January'])
Namespace(month=<Winter Month.JAN: 'January'>)
>>> parser.parse_args(['--month','March'])
usage: python.exe -m _pyrepl [-h] [--month MONTH]
python.exe -m _pyrepl: error: argument --month: invalid Winter Month value: 'March'

In this example, :meth:`!register` allows the type converter to be
referenced by its registered name instead of the class name. This approach
can improve error message clarity and provide more user-friendly output.

>>> parser.register('type', 'hexadecimal integer', lambda s: int(s, 16))
>>> parser.add_argument('--foo', type='hexadecimal integer')
_StoreAction(option_strings=['--foo'], dest='foo', nargs=None, const=None, default=None, type='hexadecimal integer', choices=None, required=False, help=None, metavar=None, deprecated=False)
>>> parser.parse_args(['--foo', '1.2'])
usage: PROG [-h] [--foo FOO]
PROG: error: argument --foo: invalid 'hexadecimal integer' value: '1.2'

Exceptions
----------
Expand Down
Loading