`Console.use_theme(theme, inherit=False)` still inherits the current styles

Open Beginner friendly
#4,259 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
1/5
Estimated time
Under an hour
Newbie friendliness
88/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
cli

Research direction

The bug is in ThemeContext.enter, which calls self.console.push_theme(self.theme) without passing the stored inherit flag; the fix is to pass inherit=self.inherit. Reproduce with the snippet in the issue, comparing push_theme(theme, inherit=False) against use_theme(theme, inherit=False) and checking that repr.number is no longer highlighted. Done when both outputs match and a test covers use_theme with inherit=False.

Written by the indexing model from the issue text.

Description

Hi! I hit this while testing themes. use_theme takes inherit and passes it to ThemeContext, which stores it but then calls self.console.push_theme(self.theme) without it, so the pushed theme always inherits.

import io
from rich.console import Console
from rich.theme import Theme

# A theme that doesn't include the default styles.
theme = Theme({"warning": "red"}, inherit=False)

def render(console):
    console.print("[warning]warning[/] 42", end="")
    out = console.file.getvalue()
    console.file.truncate(0)
    console.file.seek(0)
    return repr(out)

console = Console(file=io.StringIO(), force_terminal=True, color_system="truecolor")

console.push_theme(theme, inherit=False)
print("push_theme(theme, inherit=False):", render(console))
console.pop_theme()

with console.use_theme(theme, inherit=False):
    print("use_theme(theme, inherit=False): ", render(console))

Output on Rich 15.0.0 (and main at 3a109cc):

push_theme(theme, inherit=False): '\x1b[31mwarning\x1b[0m 42'
use_theme(theme, inherit=False):  '\x1b[31mwarning\x1b[0m \x1b[1;36m42\x1b[0m'

push_theme drops repr.number, as expected, but use_theme keeps it and the number is still highlighted. I expected both lines to match.

The fix is one line in ThemeContext.__enter__: self.console.push_theme(self.theme, inherit=self.inherit). Happy to open a PR.

Python 3.13, macOS.

Dominant language
Python
Stars
57.8k
Forks
2.6k
Avg merge
20m
Merged PRs (30d)
3

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Textualize/rich

All issues in Textualize/rich

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.