|
1 | 1 | # Author: Steven J. Bethard <steven.bethard@gmail.com>. |
2 | | -# New maintainer as of 29 August 2019: Raymond Hettinger <raymond.hettinger@gmail.com> |
3 | 2 |
|
4 | 3 | """Command-line parsing library |
5 | 4 |
|
@@ -1570,8 +1569,8 @@ def add_argument(self, *args, **kwargs): |
1570 | 1569 | f'instance of it must be passed') |
1571 | 1570 |
|
1572 | 1571 | # raise an error if the metavar does not match the type |
1573 | | - if hasattr(self, "_get_formatter"): |
1574 | | - formatter = self._get_formatter() |
| 1572 | + if hasattr(self, "_get_validation_formatter"): |
| 1573 | + formatter = self._get_validation_formatter() |
1575 | 1574 | try: |
1576 | 1575 | formatter._format_args(action, None) |
1577 | 1576 | except TypeError: |
@@ -1765,8 +1764,8 @@ def _handle_conflict_resolve(self, action, conflicting_actions): |
1765 | 1764 | action.container._remove_action(action) |
1766 | 1765 |
|
1767 | 1766 | def _check_help(self, action): |
1768 | | - if action.help and hasattr(self, "_get_formatter"): |
1769 | | - formatter = self._get_formatter() |
| 1767 | + if action.help and hasattr(self, "_get_validation_formatter"): |
| 1768 | + formatter = self._get_validation_formatter() |
1770 | 1769 | try: |
1771 | 1770 | formatter._expand_help(action) |
1772 | 1771 | except (ValueError, TypeError, KeyError) as exc: |
@@ -1921,6 +1920,9 @@ def __init__(self, |
1921 | 1920 | self.suggest_on_error = suggest_on_error |
1922 | 1921 | self.color = color |
1923 | 1922 |
|
| 1923 | + # Cached formatter for validation (avoids repeated _set_color calls) |
| 1924 | + self._cached_formatter = None |
| 1925 | + |
1924 | 1926 | add_group = self.add_argument_group |
1925 | 1927 | self._positionals = add_group(_('positional arguments')) |
1926 | 1928 | self._optionals = add_group(_('options')) |
@@ -2752,6 +2754,13 @@ def _get_formatter(self): |
2752 | 2754 | formatter._set_color(self.color) |
2753 | 2755 | return formatter |
2754 | 2756 |
|
| 2757 | + def _get_validation_formatter(self): |
| 2758 | + # Return cached formatter for read-only validation operations |
| 2759 | + # (_expand_help and _format_args). Avoids repeated _set_color calls. |
| 2760 | + if self._cached_formatter is None: |
| 2761 | + self._cached_formatter = self._get_formatter() |
| 2762 | + return self._cached_formatter |
| 2763 | + |
2755 | 2764 | # ===================== |
2756 | 2765 | # Help-printing methods |
2757 | 2766 | # ===================== |
|
0 commit comments