scope.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from collections.abc import Mapping
  2. from typing import TYPE_CHECKING, Any, Optional, Tuple
  3. from .highlighter import ReprHighlighter
  4. from .panel import Panel
  5. from .pretty import Pretty
  6. from .table import Table
  7. from .text import Text, TextType
  8. if TYPE_CHECKING:
  9. from .console import ConsoleRenderable
  10. def render_scope(
  11. scope: "Mapping[str, Any]",
  12. *,
  13. title: Optional[TextType] = None,
  14. sort_keys: bool = True,
  15. indent_guides: bool = False,
  16. max_length: Optional[int] = None,
  17. max_string: Optional[int] = None,
  18. ) -> "ConsoleRenderable":
  19. """Render python variables in a given scope.
  20. Args:
  21. scope (Mapping): A mapping containing variable names and values.
  22. title (str, optional): Optional title. Defaults to None.
  23. sort_keys (bool, optional): Enable sorting of items. Defaults to True.
  24. indent_guides (bool, optional): Enable indentaton guides. Defaults to False.
  25. max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  26. Defaults to None.
  27. max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.
  28. Returns:
  29. ConsoleRenderable: A renderable object.
  30. """
  31. highlighter = ReprHighlighter()
  32. items_table = Table.grid(padding=(0, 1), expand=False)
  33. items_table.add_column(justify="right")
  34. def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:
  35. """Sort special variables first, then alphabetically."""
  36. key, _ = item
  37. return (not key.startswith("__"), key.lower())
  38. items = sorted(scope.items(), key=sort_items) if sort_keys else scope.items()
  39. for key, value in items:
  40. key_text = Text.assemble(
  41. (key, "scope.key.special" if key.startswith("__") else "scope.key"),
  42. (" =", "scope.equals"),
  43. )
  44. items_table.add_row(
  45. key_text,
  46. Pretty(
  47. value,
  48. highlighter=highlighter,
  49. indent_guides=indent_guides,
  50. max_length=max_length,
  51. max_string=max_string,
  52. ),
  53. )
  54. return Panel.fit(
  55. items_table,
  56. title=title,
  57. border_style="scope.border",
  58. padding=(0, 1),
  59. )
  60. if __name__ == "__main__": # pragma: no cover
  61. from pip._vendor.rich import print
  62. print()
  63. def test(foo: float, bar: float) -> None:
  64. list_of_things = [1, 2, 3, None, 4, True, False, "Hello World"]
  65. dict_of_things = {
  66. "version": "1.1",
  67. "method": "confirmFruitPurchase",
  68. "params": [["apple", "orange", "mangoes", "pomelo"], 1.123],
  69. "id": "194521489",
  70. }
  71. print(render_scope(locals(), title="[i]locals", sort_keys=False))
  72. test(20.3423, 3.1427)
  73. print()