Skip to content
Merged
Changes from 11 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
40 changes: 40 additions & 0 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2162,6 +2162,46 @@ 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.

* *object* - the callable object 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.


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