Skip to content

Conversation

@chillakalyan
Copy link
Contributor

@chillakalyan chillakalyan commented Nov 16, 2025

Fixes: #141571

argparse currently initializes color twice when constructing a
HelpFormatter:

  1. HelpFormatter.init() calls _set_color(color) immediately,
    using the default value color=True.
  2. Later, argparse._get_formatter() instantiates a new formatter and
    calls formatter._set_color(self.color) again.

The first initialization is redundant and causes duplicate environment
lookups and repeated calls to colorize.can_colorize(), especially when
color=False. The actual color configuration only needs to happen once,
and the correct location is inside _get_formatter(), where formatter
instances are created.

This patch removes the early invocation of _set_color() in
HelpFormatter.init and simply stores the requested color preference:

self._color = color

The color initialization continues to happen once in
_get_formatter():

formatter._set_color(self.color)

This preserves the existing behavior for all consumers while avoiding
unnecessary work during HelpFormatter construction.

@chillakalyan chillakalyan changed the title argparse: avoid redundant early _set_color() call in HelpFormatter.__… gh-141571: argparse: avoid redundant early _set_color() call in HelpFormatter.__… Nov 16, 2025
@chillakalyan chillakalyan deleted the fix-color-main branch November 16, 2025 04:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

argparse color=False calls _set_color(True) first, then _set_color(False) -- leading to needless envirnment lookups

1 participant