How do I pretty print the source code of functions contained in a class instance's attributes? #3428
-
I would like to use from dataclasses import dataclass
import inspect
from typing import Any, Callable
from rich import print as rprint
import rich.repr
from rich.syntax import Syntax
@dataclass
class MyClass:
fs: list[Callable[..., Any]]
def __rich_repr__(self) -> rich.repr.Result:
for f in self.fs:
yield (
f.__name__,
rprint(
Syntax(
inspect.getsource(f), lexer="python", theme="lightbulb"
),
),
)
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:
How do I get |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
It's not a rich repr you need. Repr strings should be simple text. You can build a renderable that yields a Syntax object or any other builtin renderable. Have a read though the following page in the docs: |
Beta Was this translation helpful? Give feedback.
-
@willmcgugan Thank you so much for the hint: |
Beta Was this translation helpful? Give feedback.
It's not a rich repr you need. Repr strings should be simple text. You can build a renderable that yields a Syntax object or any other builtin renderable.
Have a read though the following page in the docs:
https://rich.readthedocs.io/en/latest/protocol.html