tabulate.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from collections.abc import Mapping
  2. from typing import Any, Optional
  3. import warnings
  4. from pip._vendor.rich.console import JustifyMethod
  5. from . import box
  6. from .highlighter import ReprHighlighter
  7. from .pretty import Pretty
  8. from .table import Table
  9. def tabulate_mapping(
  10. mapping: "Mapping[Any, Any]",
  11. title: Optional[str] = None,
  12. caption: Optional[str] = None,
  13. title_justify: Optional[JustifyMethod] = None,
  14. caption_justify: Optional[JustifyMethod] = None,
  15. ) -> Table:
  16. """Generate a simple table from a mapping.
  17. Args:
  18. mapping (Mapping): A mapping object (e.g. a dict);
  19. title (str, optional): Optional title to be displayed over the table.
  20. caption (str, optional): Optional caption to be displayed below the table.
  21. title_justify (str, optional): Justify method for title. Defaults to None.
  22. caption_justify (str, optional): Justify method for caption. Defaults to None.
  23. Returns:
  24. Table: A table instance which may be rendered by the Console.
  25. """
  26. warnings.warn("tabulate_mapping will be deprecated in Rich v11", DeprecationWarning)
  27. table = Table(
  28. show_header=False,
  29. title=title,
  30. caption=caption,
  31. box=box.ROUNDED,
  32. border_style="blue",
  33. )
  34. table.title = title
  35. table.caption = caption
  36. if title_justify is not None:
  37. table.title_justify = title_justify
  38. if caption_justify is not None:
  39. table.caption_justify = caption_justify
  40. highlighter = ReprHighlighter()
  41. for key, value in mapping.items():
  42. table.add_row(
  43. Pretty(key, highlighter=highlighter), Pretty(value, highlighter=highlighter)
  44. )
  45. return table