_inspect.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import inspect
  2. from inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature
  3. from typing import Any, Collection, Iterable, Optional, Tuple, Type, Union
  4. from .console import Group, RenderableType
  5. from .control import escape_control_codes
  6. from .highlighter import ReprHighlighter
  7. from .jupyter import JupyterMixin
  8. from .panel import Panel
  9. from .pretty import Pretty
  10. from .table import Table
  11. from .text import Text, TextType
  12. def _first_paragraph(doc: str) -> str:
  13. """Get the first paragraph from a docstring."""
  14. paragraph, _, _ = doc.partition("\n\n")
  15. return paragraph
  16. class Inspect(JupyterMixin):
  17. """A renderable to inspect any Python Object.
  18. Args:
  19. obj (Any): An object to inspect.
  20. title (str, optional): Title to display over inspect result, or None use type. Defaults to None.
  21. help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.
  22. methods (bool, optional): Enable inspection of callables. Defaults to False.
  23. docs (bool, optional): Also render doc strings. Defaults to True.
  24. private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.
  25. dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.
  26. sort (bool, optional): Sort attributes alphabetically. Defaults to True.
  27. all (bool, optional): Show all attributes. Defaults to False.
  28. value (bool, optional): Pretty print value of object. Defaults to True.
  29. """
  30. def __init__(
  31. self,
  32. obj: Any,
  33. *,
  34. title: Optional[TextType] = None,
  35. help: bool = False,
  36. methods: bool = False,
  37. docs: bool = True,
  38. private: bool = False,
  39. dunder: bool = False,
  40. sort: bool = True,
  41. all: bool = True,
  42. value: bool = True,
  43. ) -> None:
  44. self.highlighter = ReprHighlighter()
  45. self.obj = obj
  46. self.title = title or self._make_title(obj)
  47. if all:
  48. methods = private = dunder = True
  49. self.help = help
  50. self.methods = methods
  51. self.docs = docs or help
  52. self.private = private or dunder
  53. self.dunder = dunder
  54. self.sort = sort
  55. self.value = value
  56. def _make_title(self, obj: Any) -> Text:
  57. """Make a default title."""
  58. title_str = (
  59. str(obj)
  60. if (isclass(obj) or callable(obj) or ismodule(obj))
  61. else str(type(obj))
  62. )
  63. title_text = self.highlighter(title_str)
  64. return title_text
  65. def __rich__(self) -> Panel:
  66. return Panel.fit(
  67. Group(*self._render()),
  68. title=self.title,
  69. border_style="scope.border",
  70. padding=(0, 1),
  71. )
  72. def _get_signature(self, name: str, obj: Any) -> Optional[Text]:
  73. """Get a signature for a callable."""
  74. try:
  75. _signature = str(signature(obj)) + ":"
  76. except ValueError:
  77. _signature = "(...)"
  78. except TypeError:
  79. return None
  80. source_filename: Optional[str] = None
  81. try:
  82. source_filename = getfile(obj)
  83. except (OSError, TypeError):
  84. # OSError is raised if obj has no source file, e.g. when defined in REPL.
  85. pass
  86. callable_name = Text(name, style="inspect.callable")
  87. if source_filename:
  88. callable_name.stylize(f"link file://{source_filename}")
  89. signature_text = self.highlighter(_signature)
  90. qualname = name or getattr(obj, "__qualname__", name)
  91. # If obj is a module, there may be classes (which are callable) to display
  92. if inspect.isclass(obj):
  93. prefix = "class"
  94. elif inspect.iscoroutinefunction(obj):
  95. prefix = "async def"
  96. else:
  97. prefix = "def"
  98. qual_signature = Text.assemble(
  99. (f"{prefix} ", f"inspect.{prefix.replace(' ', '_')}"),
  100. (qualname, "inspect.callable"),
  101. signature_text,
  102. )
  103. return qual_signature
  104. def _render(self) -> Iterable[RenderableType]:
  105. """Render object."""
  106. def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:
  107. key, (_error, value) = item
  108. return (callable(value), key.strip("_").lower())
  109. def safe_getattr(attr_name: str) -> Tuple[Any, Any]:
  110. """Get attribute or any exception."""
  111. try:
  112. return (None, getattr(obj, attr_name))
  113. except Exception as error:
  114. return (error, None)
  115. obj = self.obj
  116. keys = dir(obj)
  117. total_items = len(keys)
  118. if not self.dunder:
  119. keys = [key for key in keys if not key.startswith("__")]
  120. if not self.private:
  121. keys = [key for key in keys if not key.startswith("_")]
  122. not_shown_count = total_items - len(keys)
  123. items = [(key, safe_getattr(key)) for key in keys]
  124. if self.sort:
  125. items.sort(key=sort_items)
  126. items_table = Table.grid(padding=(0, 1), expand=False)
  127. items_table.add_column(justify="right")
  128. add_row = items_table.add_row
  129. highlighter = self.highlighter
  130. if callable(obj):
  131. signature = self._get_signature("", obj)
  132. if signature is not None:
  133. yield signature
  134. yield ""
  135. if self.docs:
  136. _doc = self._get_formatted_doc(obj)
  137. if _doc is not None:
  138. doc_text = Text(_doc, style="inspect.help")
  139. doc_text = highlighter(doc_text)
  140. yield doc_text
  141. yield ""
  142. if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)):
  143. yield Panel(
  144. Pretty(obj, indent_guides=True, max_length=10, max_string=60),
  145. border_style="inspect.value.border",
  146. )
  147. yield ""
  148. for key, (error, value) in items:
  149. key_text = Text.assemble(
  150. (
  151. key,
  152. "inspect.attr.dunder" if key.startswith("__") else "inspect.attr",
  153. ),
  154. (" =", "inspect.equals"),
  155. )
  156. if error is not None:
  157. warning = key_text.copy()
  158. warning.stylize("inspect.error")
  159. add_row(warning, highlighter(repr(error)))
  160. continue
  161. if callable(value):
  162. if not self.methods:
  163. continue
  164. _signature_text = self._get_signature(key, value)
  165. if _signature_text is None:
  166. add_row(key_text, Pretty(value, highlighter=highlighter))
  167. else:
  168. if self.docs:
  169. docs = self._get_formatted_doc(value)
  170. if docs is not None:
  171. _signature_text.append("\n" if "\n" in docs else " ")
  172. doc = highlighter(docs)
  173. doc.stylize("inspect.doc")
  174. _signature_text.append(doc)
  175. add_row(key_text, _signature_text)
  176. else:
  177. add_row(key_text, Pretty(value, highlighter=highlighter))
  178. if items_table.row_count:
  179. yield items_table
  180. elif not_shown_count:
  181. yield Text.from_markup(
  182. f"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] "
  183. f"Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options."
  184. )
  185. def _get_formatted_doc(self, object_: Any) -> Optional[str]:
  186. """
  187. Extract the docstring of an object, process it and returns it.
  188. The processing consists in cleaning up the doctring's indentation,
  189. taking only its 1st paragraph if `self.help` is not True,
  190. and escape its control codes.
  191. Args:
  192. object_ (Any): the object to get the docstring from.
  193. Returns:
  194. Optional[str]: the processed docstring, or None if no docstring was found.
  195. """
  196. docs = getdoc(object_)
  197. if docs is None:
  198. return None
  199. docs = cleandoc(docs).strip()
  200. if not self.help:
  201. docs = _first_paragraph(docs)
  202. return escape_control_codes(docs)
  203. def get_object_types_mro(obj: Union[object, Type[Any]]) -> Tuple[type, ...]:
  204. """Returns the MRO of an object's class, or of the object itself if it's a class."""
  205. if not hasattr(obj, "__mro__"):
  206. # N.B. we cannot use `if type(obj) is type` here because it doesn't work with
  207. # some types of classes, such as the ones that use abc.ABCMeta.
  208. obj = type(obj)
  209. return getattr(obj, "__mro__", ())
  210. def get_object_types_mro_as_strings(obj: object) -> Collection[str]:
  211. """
  212. Returns the MRO of an object's class as full qualified names, or of the object itself if it's a class.
  213. Examples:
  214. `object_types_mro_as_strings(JSONDecoder)` will return `['json.decoder.JSONDecoder', 'builtins.object']`
  215. """
  216. return [
  217. f'{getattr(type_, "__module__", "")}.{getattr(type_, "__qualname__", "")}'
  218. for type_ in get_object_types_mro(obj)
  219. ]
  220. def is_object_one_of_types(
  221. obj: object, fully_qualified_types_names: Collection[str]
  222. ) -> bool:
  223. """
  224. Returns `True` if the given object's class (or the object itself, if it's a class) has one of the
  225. fully qualified names in its MRO.
  226. """
  227. for type_name in get_object_types_mro_as_strings(obj):
  228. if type_name in fully_qualified_types_names:
  229. return True
  230. return False