@@ -1568,8 +1568,8 @@ def add_argument(self, *args, **kwargs):
15681568 f'instance of it must be passed' )
15691569
15701570 # raise an error if the metavar does not match the type
1571- if hasattr (self , "_get_formatter " ):
1572- formatter = self ._get_formatter ()
1571+ if hasattr (self , "_get_validation_formatter " ):
1572+ formatter = self ._get_validation_formatter ()
15731573 try :
15741574 formatter ._format_args (action , None )
15751575 except TypeError :
@@ -1763,8 +1763,8 @@ def _handle_conflict_resolve(self, action, conflicting_actions):
17631763 action .container ._remove_action (action )
17641764
17651765 def _check_help (self , action ):
1766- if action .help and hasattr (self , "_get_formatter " ):
1767- formatter = self ._get_formatter ()
1766+ if action .help and hasattr (self , "_get_validation_formatter " ):
1767+ formatter = self ._get_validation_formatter ()
17681768 try :
17691769 formatter ._expand_help (action )
17701770 except (ValueError , TypeError , KeyError ) as exc :
@@ -1919,6 +1919,9 @@ def __init__(self,
19191919 self .suggest_on_error = suggest_on_error
19201920 self .color = color
19211921
1922+ # Cached formatter for validation (avoids repeated _set_color calls)
1923+ self ._cached_formatter = None
1924+
19221925 add_group = self .add_argument_group
19231926 self ._positionals = add_group (_ ('positional arguments' ))
19241927 self ._optionals = add_group (_ ('options' ))
@@ -2750,6 +2753,13 @@ def _get_formatter(self):
27502753 formatter ._set_color (self .color )
27512754 return formatter
27522755
2756+ def _get_validation_formatter (self ):
2757+ # Return cached formatter for read-only validation operations
2758+ # (_expand_help and _format_args). Avoids repeated slow _set_color calls.
2759+ if self ._cached_formatter is None :
2760+ self ._cached_formatter = self ._get_formatter ()
2761+ return self ._cached_formatter
2762+
27532763 # =====================
27542764 # Help-printing methods
27552765 # =====================
0 commit comments