add_argument(dest, ..., name=value, ...) add_argument(option_string, option_string, ..., name=value, ...)
(self, *args, **kwargs)
| 1500 | # ======================= |
| 1501 | |
| 1502 | def add_argument(self, *args, **kwargs): |
| 1503 | """ |
| 1504 | add_argument(dest, ..., name=value, ...) |
| 1505 | add_argument(option_string, option_string, ..., name=value, ...) |
| 1506 | """ |
| 1507 | |
| 1508 | # if no positional args are supplied or only one is supplied and |
| 1509 | # it doesn't look like an option string, parse a positional |
| 1510 | # argument |
| 1511 | chars = self.prefix_chars |
| 1512 | if not args or len(args) == 1 and args[0][0] not in chars: |
| 1513 | if args and 'dest' in kwargs: |
| 1514 | raise TypeError('dest supplied twice for positional argument,' |
| 1515 | ' did you mean metavar?') |
| 1516 | kwargs = self._get_positional_kwargs(*args, **kwargs) |
| 1517 | |
| 1518 | # otherwise, we're adding an optional argument |
| 1519 | else: |
| 1520 | kwargs = self._get_optional_kwargs(*args, **kwargs) |
| 1521 | |
| 1522 | # if no default was supplied, use the parser-level default |
| 1523 | if 'default' not in kwargs: |
| 1524 | dest = kwargs['dest'] |
| 1525 | if dest in self._defaults: |
| 1526 | kwargs['default'] = self._defaults[dest] |
| 1527 | elif self.argument_default is not None: |
| 1528 | kwargs['default'] = self.argument_default |
| 1529 | |
| 1530 | # create the action object, and add it to the parser |
| 1531 | action_name = kwargs.get('action') |
| 1532 | action_class = self._pop_action_class(kwargs) |
| 1533 | if not callable(action_class): |
| 1534 | raise ValueError(f'unknown action {action_class!r}') |
| 1535 | action = action_class(**kwargs) |
| 1536 | |
| 1537 | # raise an error if action for positional argument does not |
| 1538 | # consume arguments |
| 1539 | if not action.option_strings and action.nargs == 0: |
| 1540 | raise ValueError(f'action {action_name!r} is not valid for positional arguments') |
| 1541 | |
| 1542 | # raise an error if the action type is not callable |
| 1543 | type_func = self._registry_get('type', action.type, action.type) |
| 1544 | if not callable(type_func): |
| 1545 | raise TypeError(f'{type_func!r} is not callable') |
| 1546 | |
| 1547 | if type_func is FileType: |
| 1548 | raise TypeError(f'{type_func!r} is a FileType class object, ' |
| 1549 | f'instance of it must be passed') |
| 1550 | |
| 1551 | # raise an error if the metavar does not match the type |
| 1552 | if hasattr(self, "_get_validation_formatter"): |
| 1553 | formatter = self._get_validation_formatter() |
| 1554 | try: |
| 1555 | formatter._format_args(action, None) |
| 1556 | except TypeError: |
| 1557 | raise ValueError("length of metavar tuple does not match nargs") |
| 1558 | self._check_help(action) |
| 1559 | return self._add_action(action) |
nothing calls this directly
no test coverage detected