Skip to content

[REQUEST] Allow classes as renderables #3741

Closed
@buhrmann

Description

@buhrmann

Hi, I'd like to be able to pretty print both instances as well as classes using the __rich_console__ protocol (specifically in the context of pydantic models). In theory this can be achieved using Descriptors, like so:

class RichConsole:
    def __get__(self, ins, cls):
        if ins is None:
            return cls.__cls_rich_console__

        return ins.__inst_rich_console__


class Model:

    def __inst_rich_console__(self, console, options):
        yield Text("Hello instance!!!")

    @classmethod
    def __cls_rich_console__(cls, console, options):
        yield Text("Hello class!!!")

    __rich_console__ = RichConsole()


m = Model()
print(m)
print(Model)

which produces something like

Hello instance!!!
Hello class!!!

But only if I remove the isclass check here:

if hasattr(renderable, "__rich_console__") and not isclass(renderable):

I'm sure the check is there for a good reason, but would there be a way to allow this in some other way?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions