Skip to content

gh-148823: Avoid importing _colorize when creating an ArgumentParser#148827

Open
DavidCEllis wants to merge 4 commits intopython:mainfrom
DavidCEllis:defer-colorize-argparse
Open

gh-148823: Avoid importing _colorize when creating an ArgumentParser#148827
DavidCEllis wants to merge 4 commits intopython:mainfrom
DavidCEllis:defer-colorize-argparse

Conversation

@DavidCEllis
Copy link
Copy Markdown
Contributor

@DavidCEllis DavidCEllis commented Apr 21, 2026

This is one approach to deferring the _colorize import further.

This makes ._theme and ._decolor into properties so that _colorize is no longer imported when _set_color is called, but only when the theme is accessed.

Currently to prevent the import from subsequently being triggered when a subparser is created, this adds a 'fake' _colorless_theme which just returns empty strings for all attributes which replaces the actual colourless theme from _colorize.

Effectively this is what the colourless theme from _colorize does. I wanted to avoid duplicating all of the attribute names here or further complicating the logic, but there may be a better way to handle this.

Testing this did require an addition to the ensure_lazy_imports test helper to allow running additional code before checking for lazy imports. I think this might also be useful elsewhere when testing imports aren't being triggered earlier than intended.

Command: ./python -c 'import argparse; argparse.ArgumentParser()'

Benchmark 1: main
  Time (mean ± σ):      28.7 ms ±   3.3 ms    [User: 24.1 ms, System: 4.3 ms]
  Range (min … max):    22.2 ms …  46.4 ms    200 runs
 
Benchmark 2: lazy colorize
  Time (mean ± σ):      21.6 ms ±   5.8 ms    [User: 17.3 ms, System: 4.0 ms]
  Range (min … max):    12.1 ms …  36.0 ms    200 runs
 
Summary
  lazy colorize ran
    1.33 ± 0.39 times faster than main

Note that this uses the new lazy imports, this would need significant tweaking if it were to be backported to 3.14.

This uses a new lazy import so it works with short circuiting alongside a `_colorless_theme` object to prevent the `_colorize` import if color is set to False.

_theme and _decolor are now properties to prevent `_set_color` from performing the imports on creation of a formatter.
@DavidCEllis
Copy link
Copy Markdown
Contributor Author

Ah this pinged more people than I had anticipated.

This appears to be due to the modification to import_helper.py to allow for testing lazy imports with additional logic.

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.

1 participant