protocol.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from typing import Any, Callable, cast, Set, TYPE_CHECKING
  2. from inspect import isclass
  3. if TYPE_CHECKING:
  4. from pip._vendor.rich.console import RenderableType
  5. _GIBBERISH = """aihwerij235234ljsdnp34ksodfipwoe234234jlskjdf"""
  6. def is_renderable(check_object: Any) -> bool:
  7. """Check if an object may be rendered by Rich."""
  8. return (
  9. isinstance(check_object, str)
  10. or hasattr(check_object, "__rich__")
  11. or hasattr(check_object, "__rich_console__")
  12. )
  13. def rich_cast(renderable: object) -> "RenderableType":
  14. """Cast an object to a renderable by calling __rich__ if present.
  15. Args:
  16. renderable (object): A potentially renderable object
  17. Returns:
  18. object: The result of recursively calling __rich__.
  19. """
  20. from pip._vendor.rich.console import RenderableType
  21. rich_visited_set: Set[type] = set() # Prevent potential infinite loop
  22. while hasattr(renderable, "__rich__") and not isclass(renderable):
  23. # Detect object which claim to have all the attributes
  24. if hasattr(renderable, _GIBBERISH):
  25. return repr(renderable)
  26. cast_method = getattr(renderable, "__rich__")
  27. renderable = cast_method()
  28. renderable_type = type(renderable)
  29. if renderable_type in rich_visited_set:
  30. break
  31. rich_visited_set.add(renderable_type)
  32. return cast(RenderableType, renderable)