Search code examples
pythonpython-3.xrich

Colorizing Text within Rich Tree


Im building some trees within Rich. However Im outputting obj repr() and also Python object details that Rich only seems to want to display if I pass the data to the tree branch as a string. i.e.

tree = Tree(str(type(root_obj)))

My question is this out can i colourize the output of my tree in Rich. For example if I pass a type to the tree without casting it to a string I get:

tree = Tree(type(root_obj))
...
rich.errors.NotRenderableError: Unable to render <class 'nornir.core.task.AggregatedResult'>; A str, Segment or object with __rich_console__ method is required

But not sure what console method to use here. Any help would be great. Thanks.


Solution

  • You can highlight text via a Rich highlighter. The ReprHighlighter will highlight the strings produces from most objects. Import it like this:

    from rich.highlighter import ReprHighlighter
    highlighter = ReprHighlighter()
    

    Now you can highlight strings in the following way:

    tree = Tree(highlighter(str(root_obj)))
    

    Alternatively, you can use Rich's pretty printing capabilities via the rich.pretty.Pretty class:

    from rich.pretty import Pretty
    
    tree = Tree(Pretty(rich_obj))