Skip to content

_colorize: LiveProfiler.no_colors() sets int and Literal fields to "" #158236

Description

@Tony123-tech

Lib/_colorize.py has a type-contract violation in
ThemeSection.no_colors(). It assumes every field is a str ANSI
escape and sets them all to "":

@classmethod
def no_colors(cls) -> Self:
    color_state: dict[str, str] = {}
    for color_name in cls.__dataclass_fields__:
        color_state[color_name] = ""
    return cls(**color_state)

But LiveProfiler (line 261) has int fields (CursesColors.*) and a
Literal["dark", "light"] field (background_style). Overriding them
to "" breaks the type contract.

Reproduction:

from _colorize import LiveProfiler, theme_no_color
print(repr(LiveProfiler.no_colors().title_fg))          # ''
print(repr(LiveProfiler.no_colors().background_style))  # ''
print(repr(theme_no_color.live_profiler.title_fg))      # ''
print(repr(theme_no_color.live_profiler.background_style))  # ''

Expected: title_fg is an int (CursesColors.*), background_style is
'dark' or 'light'.

Compare with the default theme, which is correct:

from _colorize import default_theme
print(repr(default_theme.live_profiler.title_fg))          # 6
print(repr(default_theme.live_profiler.background_style))  # 'dark'

Impact: any consumer of theme_no_color.live_profiler that passes
title_fg to curses.init_pair or curses.color_pair will get
TypeError: an integer is required, or a silently wrong color.

Possible fixes:

  1. Override LiveProfiler.no_colors() to set int fields to
    CursesColors.DEFAULT (-1) and leave background_style at 'dark'.
  2. Make ThemeSection.no_colors() aware of field types.
  3. Add a parameter to no_colors() specifying the "no color" value.

I'd like to submit a PR once a direction is agreed on.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions