I would like to use rich
to pretty print a Python class like so:
from dataclasses import dataclass
import inspect
from typing import Any, Callable
from rich import print as rprint
import rich.repr
@dataclass
class MyClass:
fs: list[Callable[..., Any]]
def __rich_repr__(self) -> rich.repr.Result:
for f in self.fs:
yield inspect.getsource(f)
def g(x: int, y: str) -> list[str]:
return [y] * x
def h(y: str, zs: list[str]) -> str:
return " ".join([y + z for z in zs])
my_class = MyClass([g, h])
rprint(my_class)
Which produces as output, roughly:
MyClass(
'def g(x: int, y: str) -> list[str]:n return [y] * xn',
'def h(y: str, zs: list[str]) -> str:n return " ".join([y + z for z in zs])n'
)
How do I get rich
to pretty print the source strings of the functions? I figured that Pretty
has something to do with it, but couldn’t quite get it to work.