_inspect.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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, callables at the top, leading and trailing underscores ignored. 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 not isinstance(qualname, str):
  92. qualname = getattr(obj, "__name__", name)
  93. if not isinstance(qualname, str):
  94. qualname = name
  95. # If obj is a module, there may be classes (which are callable) to display
  96. if inspect.isclass(obj):
  97. prefix = "class"
  98. elif inspect.iscoroutinefunction(obj):
  99. prefix = "async def"
  100. else:
  101. prefix = "def"
  102. qual_signature = Text.assemble(
  103. (f"{prefix} ", f"inspect.{prefix.replace(' ', '_')}"),
  104. (qualname, "inspect.callable"),
  105. signature_text,
  106. )
  107. return qual_signature
  108. def _render(self) -> Iterable[RenderableType]:
  109. """Render object."""
  110. def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:
  111. key, (_error, value) = item
  112. return (callable(value), key.strip("_").lower())
  113. def safe_getattr(attr_name: str) -> Tuple[Any, Any]:
  114. """Get attribute or any exception."""
  115. try:
  116. return (None, getattr(obj, attr_name))
  117. except Exception as error:
  118. return (error, None)
  119. obj = self.obj
  120. keys = dir(obj)
  121. total_items = len(keys)
  122. if not self.dunder:
  123. keys = [key for key in keys if not key.startswith("__")]
  124. if not self.private:
  125. keys = [key for key in keys if not key.startswith("_")]
  126. not_shown_count = total_items - len(keys)
  127. items = [(key, safe_getattr(key)) for key in keys]
  128. if self.sort:
  129. items.sort(key=sort_items)
  130. items_table = Table.grid(padding=(0, 1), expand=False)
  131. items_table.add_column(justify="right")
  132. add_row = items_table.add_row
  133. highlighter = self.highlighter
  134. if callable(obj):
  135. signature = self._get_signature("", obj)
  136. if signature is not None:
  137. yield signature
  138. yield ""
  139. if self.docs:
  140. _doc = self._get_formatted_doc(obj)
  141. if _doc is not None:
  142. doc_text = Text(_doc, style="inspect.help")
  143. doc_text = highlighter(doc_text)
  144. yield doc_text
  145. yield ""
  146. if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)):
  147. yield Panel(
  148. Pretty(obj, indent_guides=True, max_length=10, max_string=60),
  149. border_style="inspect.value.border",
  150. )
  151. yield ""
  152. for key, (error, value) in items:
  153. key_text = Text.assemble(
  154. (
  155. key,
  156. "inspect.attr.dunder" if key.startswith("__") else "inspect.attr",
  157. ),
  158. (" =", "inspect.equals"),
  159. )
  160. if error is not None:
  161. warning = key_text.copy()
  162. warning.stylize("inspect.error")
  163. add_row(warning, highlighter(repr(error)))
  164. continue
  165. if callable(value):
  166. if not self.methods:
  167. continue
  168. _signature_text = self._get_signature(key, value)
  169. if _signature_text is None:
  170. add_row(key_text, Pretty(value, highlighter=highlighter))
  171. else:
  172. if self.docs:
  173. docs = self._get_formatted_doc(value)
  174. if docs is not None:
  175. _signature_text.append("\n" if "\n" in docs else " ")
  176. doc = highlighter(docs)
  177. doc.stylize("inspect.doc")
  178. _signature_text.append(doc)
  179. add_row(key_text, _signature_text)
  180. else:
  181. add_row(key_text, Pretty(value, highlighter=highlighter))
  182. if items_table.row_count:
  183. yield items_table
  184. elif not_shown_count:
  185. yield Text.from_markup(
  186. f"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] "
  187. f"Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options."
  188. )
  189. def _get_formatted_doc(self, object_: Any) -> Optional[str]:
  190. """
  191. Extract the docstring of an object, process it and returns it.
  192. The processing consists in cleaning up the docstring's indentation,
  193. taking only its 1st paragraph if `self.help` is not True,
  194. and escape its control codes.
  195. Args:
  196. object_ (Any): the object to get the docstring from.
  197. Returns:
  198. Optional[str]: the processed docstring, or None if no docstring was found.
  199. """
  200. docs = getdoc(object_)
  201. if docs is None:
  202. return None
  203. docs = cleandoc(docs).strip()
  204. if not self.help:
  205. docs = _first_paragraph(docs)
  206. return escape_control_codes(docs)
  207. def get_object_types_mro(obj: Union[object, Type[Any]]) -> Tuple[type, ...]:
  208. """Returns the MRO of an object's class, or of the object itself if it's a class."""
  209. if not hasattr(obj, "__mro__"):
  210. # N.B. we cannot use `if type(obj) is type` here because it doesn't work with
  211. # some types of classes, such as the ones that use abc.ABCMeta.
  212. obj = type(obj)
  213. return getattr(obj, "__mro__", ())
  214. def get_object_types_mro_as_strings(obj: object) -> Collection[str]:
  215. """
  216. Returns the MRO of an object's class as full qualified names, or of the object itself if it's a class.
  217. Examples:
  218. `object_types_mro_as_strings(JSONDecoder)` will return `['json.decoder.JSONDecoder', 'builtins.object']`
  219. """
  220. return [
  221. f'{getattr(type_, "__module__", "")}.{getattr(type_, "__qualname__", "")}'
  222. for type_ in get_object_types_mro(obj)
  223. ]
  224. def is_object_one_of_types(
  225. obj: object, fully_qualified_types_names: Collection[str]
  226. ) -> bool:
  227. """
  228. Returns `True` if the given object's class (or the object itself, if it's a class) has one of the
  229. fully qualified names in its MRO.
  230. """
  231. for type_name in get_object_types_mro_as_strings(obj):
  232. if type_name in fully_qualified_types_names:
  233. return True
  234. return False