这是indexloc提供的服务,不要输入任何密码
Skip to content

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

@hroncok

Description

@hroncok

Bug report

Bug description:

When debugging another problem (reported in #141570) I realized that in 734e15b, an explicit color argument of self.formatter_class initialization was replaced with a subsequent formatter._set_color(self.color) call. This was done for a good reason -- backwards compatibility.

However, it also leads to unnecessary call of HelpFormatter._set_color(True) in HelpFormatter.__init__, followed by immediate call of HelpFormatter._set_color(color).

  • When color is False -- there is a needless lookup for all the environment variables as done in _colorize.can_colorize().
  • When color is True -- _colorize.can_colorize() needlessly runs twice.

Perhaps this could be optimized by:

  • Replacing HelpFormatter._set_color(color) with HelpFormatter._color = color
  • Making self._theme and self._decolor (possibly cached) properties (that change the returned value based on self._color

That way, the code would only run the potentially expensive checks when needed and only once. If this sounds lieka good idea, I can check if it's indeed that simple.

CPython versions tested on:

3.14

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.14bugs and security fixes3.15new features, bugs and security fixesstdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions