]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-142267: Cache formatter to avoid repeated `_set_color` calls (#142268)
authorSavannah Ostrowski <savannah@python.org>
Fri, 5 Dec 2025 16:47:50 +0000 (08:47 -0800)
committerGitHub <noreply@github.com>
Fri, 5 Dec 2025 16:47:50 +0000 (16:47 +0000)
Lib/argparse.py
Misc/NEWS.d/next/Library/2025-12-04-23-26-12.gh-issue-142267.yOM6fP.rst [new file with mode: 0644]

index 41467707d393c07a988c1628ef8898bb78e1ce48..10393b6a02b0bedb0de269e7a5cd982c20029b25 100644 (file)
@@ -1568,8 +1568,8 @@ class _ActionsContainer(object):
                             f'instance of it must be passed')
 
         # raise an error if the metavar does not match the type
-        if hasattr(self, "_get_formatter"):
-            formatter = self._get_formatter()
+        if hasattr(self, "_get_validation_formatter"):
+            formatter = self._get_validation_formatter()
             try:
                 formatter._format_args(action, None)
             except TypeError:
@@ -1763,8 +1763,8 @@ class _ActionsContainer(object):
                 action.container._remove_action(action)
 
     def _check_help(self, action):
-        if action.help and hasattr(self, "_get_formatter"):
-            formatter = self._get_formatter()
+        if action.help and hasattr(self, "_get_validation_formatter"):
+            formatter = self._get_validation_formatter()
             try:
                 formatter._expand_help(action)
             except (ValueError, TypeError, KeyError) as exc:
@@ -1919,6 +1919,9 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
         self.suggest_on_error = suggest_on_error
         self.color = color
 
+        # Cached formatter for validation (avoids repeated _set_color calls)
+        self._cached_formatter = None
+
         add_group = self.add_argument_group
         self._positionals = add_group(_('positional arguments'))
         self._optionals = add_group(_('options'))
@@ -2750,6 +2753,13 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer):
         formatter._set_color(self.color)
         return formatter
 
+    def _get_validation_formatter(self):
+        # Return cached formatter for read-only validation operations
+        # (_expand_help and _format_args). Avoids repeated slow _set_color calls.
+        if self._cached_formatter is None:
+            self._cached_formatter = self._get_formatter()
+        return self._cached_formatter
+
     # =====================
     # Help-printing methods
     # =====================
diff --git a/Misc/NEWS.d/next/Library/2025-12-04-23-26-12.gh-issue-142267.yOM6fP.rst b/Misc/NEWS.d/next/Library/2025-12-04-23-26-12.gh-issue-142267.yOM6fP.rst
new file mode 100644 (file)
index 0000000..f46e821
--- /dev/null
@@ -0,0 +1 @@
+Improve :mod:`argparse` performance by caching the formatter used for argument validation.