@@ -1552,8 +1552,8 @@ def add_argument(self, *args, **kwargs):
15521552 f'instance of it must be passed' )
15531553
15541554 # raise an error if the metavar does not match the type
1555- if hasattr (self , "_get_formatter " ):
1556- formatter = self ._get_formatter ()
1555+ if hasattr (self , "_get_validation_formatter " ):
1556+ formatter = self ._get_validation_formatter ()
15571557 try :
15581558 formatter ._format_args (action , None )
15591559 except TypeError :
@@ -1741,8 +1741,8 @@ def _handle_conflict_resolve(self, action, conflicting_actions):
17411741 action .container ._remove_action (action )
17421742
17431743 def _check_help (self , action ):
1744- if action .help and hasattr (self , "_get_formatter " ):
1745- formatter = self ._get_formatter ()
1744+ if action .help and hasattr (self , "_get_validation_formatter " ):
1745+ formatter = self ._get_validation_formatter ()
17461746 try :
17471747 formatter ._expand_help (action )
17481748 except (ValueError , TypeError , KeyError ) as exc :
@@ -1897,6 +1897,9 @@ def __init__(self,
18971897 self .suggest_on_error = suggest_on_error
18981898 self .color = color
18991899
1900+ # Cached formatter for validation (avoids repeated _set_color calls)
1901+ self ._cached_formatter = None
1902+
19001903 add_group = self .add_argument_group
19011904 self ._positionals = add_group (_ ('positional arguments' ))
19021905 self ._optionals = add_group (_ ('options' ))
@@ -2728,6 +2731,13 @@ def _get_formatter(self):
27282731 formatter ._set_color (self .color )
27292732 return formatter
27302733
2734+ def _get_validation_formatter (self ):
2735+ # Return cached formatter for read-only validation operations
2736+ # (_expand_help and _format_args). Avoids repeated slow _set_color calls.
2737+ if self ._cached_formatter is None :
2738+ self ._cached_formatter = self ._get_formatter ()
2739+ return self ._cached_formatter
2740+
27312741 # =====================
27322742 # Help-printing methods
27332743 # =====================
0 commit comments