Skip to content

Commit 3db10c5

Browse files
Cache validation formatter to avoid duplicative get_formatter
1 parent 2dac9e6 commit 3db10c5

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

Lib/argparse.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# Author: Steven J. Bethard <steven.bethard@gmail.com>.
2-
# New maintainer as of 29 August 2019: Raymond Hettinger <raymond.hettinger@gmail.com>
32

43
"""Command-line parsing library
54
@@ -1570,8 +1569,8 @@ def add_argument(self, *args, **kwargs):
15701569
f'instance of it must be passed')
15711570

15721571
# 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()
15751574
try:
15761575
formatter._format_args(action, None)
15771576
except TypeError:
@@ -1765,8 +1764,8 @@ def _handle_conflict_resolve(self, action, conflicting_actions):
17651764
action.container._remove_action(action)
17661765

17671766
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()
17701769
try:
17711770
formatter._expand_help(action)
17721771
except (ValueError, TypeError, KeyError) as exc:
@@ -1921,6 +1920,9 @@ def __init__(self,
19211920
self.suggest_on_error = suggest_on_error
19221921
self.color = color
19231922

1923+
# Cached formatter for validation (avoids repeated _set_color calls)
1924+
self._cached_formatter = None
1925+
19241926
add_group = self.add_argument_group
19251927
self._positionals = add_group(_('positional arguments'))
19261928
self._optionals = add_group(_('options'))
@@ -2752,6 +2754,13 @@ def _get_formatter(self):
27522754
formatter._set_color(self.color)
27532755
return formatter
27542756

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+
27552764
# =====================
27562765
# Help-printing methods
27572766
# =====================

0 commit comments

Comments
 (0)