MCPcopy Index your code
hub / github.com/python/cpython / add_argument

Method add_argument

Lib/argparse.py:1578–1635  ·  view source on GitHub ↗

add_argument(dest, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...)

(self, *args, **kwargs)

Source from the content-addressed store, hash-verified

1576 # =======================
1577
1578 def add_argument(self, *args, **kwargs):
1579 """
1580 add_argument(dest, ..., name=value, ...)
1581 add_argument(option_string, option_string, ..., name=value, ...)
1582 """
1583
1584 # if no positional args are supplied or only one is supplied and
1585 # it doesn't look like an option string, parse a positional
1586 # argument
1587 chars = self.prefix_chars
1588 if not args or len(args) == 1 and args[0][0] not in chars:
1589 if args and 'dest' in kwargs:
1590 raise TypeError('dest supplied twice for positional argument,'
1591 ' did you mean metavar?')
1592 kwargs = self._get_positional_kwargs(*args, **kwargs)
1593
1594 # otherwise, we're adding an optional argument
1595 else:
1596 kwargs = self._get_optional_kwargs(*args, **kwargs)
1597
1598 # if no default was supplied, use the parser-level default
1599 if 'default' not in kwargs:
1600 dest = kwargs['dest']
1601 if dest in self._defaults:
1602 kwargs['default'] = self._defaults[dest]
1603 elif self.argument_default is not None:
1604 kwargs['default'] = self.argument_default
1605
1606 # create the action object, and add it to the parser
1607 action_name = kwargs.get('action')
1608 action_class = self._pop_action_class(kwargs)
1609 if not callable(action_class):
1610 raise ValueError(f'unknown action {action_class!r}')
1611 action = action_class(**kwargs)
1612
1613 # raise an error if action for positional argument does not
1614 # consume arguments
1615 if not action.option_strings and action.nargs == 0:
1616 raise ValueError(f'action {action_name!r} is not valid for positional arguments')
1617
1618 # raise an error if the action type is not callable
1619 type_func = self._registry_get('type', action.type, action.type)
1620 if not callable(type_func):
1621 raise TypeError(f'{type_func!r} is not callable')
1622
1623 if type_func is FileType:
1624 raise TypeError(f'{type_func!r} is a FileType class object, '
1625 f'instance of it must be passed')
1626
1627 # raise an error if the metavar does not match the type
1628 if hasattr(self, "_get_validation_formatter"):
1629 formatter = self._get_validation_formatter()
1630 try:
1631 formatter._format_args(action, None)
1632 except TypeError:
1633 raise ValueError("length of metavar tuple does not match nargs")
1634 self._check_help(action)
1635 return self._add_action(action)

Callers

nothing calls this directly

Calls 9

_get_optional_kwargsMethod · 0.95
_pop_action_classMethod · 0.95
_registry_getMethod · 0.95
_check_helpMethod · 0.95
_add_actionMethod · 0.95
_format_argsMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected