__init__.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. """Rich text and beautiful formatting in the terminal."""
  2. import os
  3. from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union
  4. from ._extension import load_ipython_extension # noqa: F401
  5. __all__ = ["get_console", "reconfigure", "print", "inspect", "print_json"]
  6. if TYPE_CHECKING:
  7. from .console import Console
  8. # Global console used by alternative print
  9. _console: Optional["Console"] = None
  10. try:
  11. _IMPORT_CWD = os.path.abspath(os.getcwd())
  12. except FileNotFoundError:
  13. # Can happen if the cwd has been deleted
  14. _IMPORT_CWD = ""
  15. def get_console() -> "Console":
  16. """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console,
  17. and hasn't been explicitly given one.
  18. Returns:
  19. Console: A console instance.
  20. """
  21. global _console
  22. if _console is None:
  23. from .console import Console
  24. _console = Console()
  25. return _console
  26. def reconfigure(*args: Any, **kwargs: Any) -> None:
  27. """Reconfigures the global console by replacing it with another.
  28. Args:
  29. *args (Any): Positional arguments for the replacement :class:`~rich.console.Console`.
  30. **kwargs (Any): Keyword arguments for the replacement :class:`~rich.console.Console`.
  31. """
  32. from rich.console import Console
  33. new_console = Console(*args, **kwargs)
  34. _console = get_console()
  35. _console.__dict__ = new_console.__dict__
  36. def print(
  37. *objects: Any,
  38. sep: str = " ",
  39. end: str = "\n",
  40. file: Optional[IO[str]] = None,
  41. flush: bool = False,
  42. ) -> None:
  43. r"""Print object(s) supplied via positional arguments.
  44. This function has an identical signature to the built-in print.
  45. For more advanced features, see the :class:`~rich.console.Console` class.
  46. Args:
  47. sep (str, optional): Separator between printed objects. Defaults to " ".
  48. end (str, optional): Character to write at end of output. Defaults to "\\n".
  49. file (IO[str], optional): File to write to, or None for stdout. Defaults to None.
  50. flush (bool, optional): Has no effect as Rich always flushes output. Defaults to False.
  51. """
  52. from .console import Console
  53. write_console = get_console() if file is None else Console(file=file)
  54. return write_console.print(*objects, sep=sep, end=end)
  55. def print_json(
  56. json: Optional[str] = None,
  57. *,
  58. data: Any = None,
  59. indent: Union[None, int, str] = 2,
  60. highlight: bool = True,
  61. skip_keys: bool = False,
  62. ensure_ascii: bool = False,
  63. check_circular: bool = True,
  64. allow_nan: bool = True,
  65. default: Optional[Callable[[Any], Any]] = None,
  66. sort_keys: bool = False,
  67. ) -> None:
  68. """Pretty prints JSON. Output will be valid JSON.
  69. Args:
  70. json (str): A string containing JSON.
  71. data (Any): If json is not supplied, then encode this data.
  72. indent (int, optional): Number of spaces to indent. Defaults to 2.
  73. highlight (bool, optional): Enable highlighting of output: Defaults to True.
  74. skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.
  75. ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.
  76. check_circular (bool, optional): Check for circular references. Defaults to True.
  77. allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.
  78. default (Callable, optional): A callable that converts values that can not be encoded
  79. in to something that can be JSON encoded. Defaults to None.
  80. sort_keys (bool, optional): Sort dictionary keys. Defaults to False.
  81. """
  82. get_console().print_json(
  83. json,
  84. data=data,
  85. indent=indent,
  86. highlight=highlight,
  87. skip_keys=skip_keys,
  88. ensure_ascii=ensure_ascii,
  89. check_circular=check_circular,
  90. allow_nan=allow_nan,
  91. default=default,
  92. sort_keys=sort_keys,
  93. )
  94. def inspect(
  95. obj: Any,
  96. *,
  97. console: Optional["Console"] = None,
  98. title: Optional[str] = None,
  99. help: bool = False,
  100. methods: bool = False,
  101. docs: bool = True,
  102. private: bool = False,
  103. dunder: bool = False,
  104. sort: bool = True,
  105. all: bool = False,
  106. value: bool = True,
  107. ) -> None:
  108. """Inspect any Python object.
  109. * inspect(<OBJECT>) to see summarized info.
  110. * inspect(<OBJECT>, methods=True) to see methods.
  111. * inspect(<OBJECT>, help=True) to see full (non-abbreviated) help.
  112. * inspect(<OBJECT>, private=True) to see private attributes (single underscore).
  113. * inspect(<OBJECT>, dunder=True) to see attributes beginning with double underscore.
  114. * inspect(<OBJECT>, all=True) to see all attributes.
  115. Args:
  116. obj (Any): An object to inspect.
  117. title (str, optional): Title to display over inspect result, or None use type. Defaults to None.
  118. help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.
  119. methods (bool, optional): Enable inspection of callables. Defaults to False.
  120. docs (bool, optional): Also render doc strings. Defaults to True.
  121. private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.
  122. dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.
  123. sort (bool, optional): Sort attributes alphabetically. Defaults to True.
  124. all (bool, optional): Show all attributes. Defaults to False.
  125. value (bool, optional): Pretty print value. Defaults to True.
  126. """
  127. _console = console or get_console()
  128. from rich._inspect import Inspect
  129. # Special case for inspect(inspect)
  130. is_inspect = obj is inspect
  131. _inspect = Inspect(
  132. obj,
  133. title=title,
  134. help=is_inspect or help,
  135. methods=is_inspect or methods,
  136. docs=is_inspect or docs,
  137. private=private,
  138. dunder=dunder,
  139. sort=sort,
  140. all=all,
  141. value=value,
  142. )
  143. _console.print(_inspect)
  144. if __name__ == "__main__": # pragma: no cover
  145. print("Hello, **World**")