_inspect.py 9.5 KB

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