Coverage for src/homeassistant_repl/local_help.py: 95%

109 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-17 19:05 +0000

1"""`help()` for code that runs here rather than inside Home Assistant - API 

2client mode's `obj`, live mode's `sql` and its results, anything of your own. 

3 

4The same idea as the server's condensed help (custom_components/ 

5ha_repl_server/session.py, `_class_summary`), written again here rather 

6than shared, like the rest of the two sides: what an object is for and what 

7you can call on it, not pydoc's full page - which for a class adds every 

8special method, inherited method, data descriptor and the method resolution 

9order. 

10`help(thing, full=True)` is that full page. 

11 

12`show()` is here on the same terms: the server's own (session.py, `show`) 

13sends back a picture of an object that only exists inside Home Assistant; 

14this one is for an object that is already here, which rich can be handed 

15directly. 

16""" 

17 

18from __future__ import annotations 

19 

20import dataclasses 

21import inspect 

22import pydoc 

23import sys 

24import textwrap 

25from typing import Any 

26 

27from rich.console import Console 

28from rich.pretty import Pretty 

29from rich.text import Text 

30 

31from .render import _Struct 

32 

33_INTRO = ( 

34 "help(thing) summarises an object: what it is, and its methods, " 

35 "properties and attributes.\n" 

36 "help(thing, full=True) is Python's own full help page: every method's " 

37 "docstring, special methods, inherited members and data descriptors.\n\n" 

38 "e.g. help(obj), help(sql) or help(sql.table('states'))" 

39) 

40 

41 

42def make_help(console: Console) -> Any: 

43 """A `help` that prints to this console.""" 

44 

45 def shell_help(*args: Any, full: bool = False) -> None: 

46 if not args: 

47 # Python's own help() with no arguments starts an interactive 

48 # prompt, which has no place inside this one. 

49 console.print(_INTRO, markup=False, highlight=False) 

50 return 

51 if len(args) > 1: 51 ↛ 52line 51 didn't jump to line 52 because the condition on line 51 was never true

52 raise TypeError(f"help() takes one object, not {len(args)}") 

53 (thing,) = args 

54 if full or not _is_summarisable(thing): 

55 # An explicit output, so pydoc writes the page out rather than 

56 # opening a pager on top of the shell. 

57 pydoc.Helper(output=sys.stdout)(thing) 

58 return 

59 console.print(_summary(thing, console.width)) 

60 

61 return shell_help 

62 

63 

64# What rich lays out well as it stands; anything else is shown by its attributes. 

65_AS_THEY_ARE: tuple[type, ...] = ( 

66 *(bool, int, float, complex, str, bytes, bytearray), 

67 *(dict, list, tuple, set, frozenset), 

68) 

69 

70 

71class Shown: 

72 """What show() returns: the object, with how it is to be laid out when 

73 echoed as the last expression.""" 

74 

75 def __init__(self, target: Any, **limits: Any) -> None: 

76 self._target = target 

77 self._limits = limits 

78 

79 def __rich__(self) -> Pretty: 

80 return Pretty(self._target, **self._limits) 

81 

82 def __repr__(self) -> str: 

83 return repr(self._target) 

84 

85 

86def show( 

87 thing: Any, 

88 *, 

89 private: bool = False, 

90 methods: bool = False, 

91 depth: int = 1, 

92 max_items: int = 30, 

93 max_string: int = 200, 

94) -> Shown: 

95 """Look inside an object: its attributes and their values, laid out 

96 one to a line. Names starting with an underscore are left out unless 

97 `private`, and methods unless `methods`, which lists them with their 

98 signatures. Properties are read, as that is where much of an object's 

99 state is. 

100 

101 Long values are cut short: a container to its first `max_items`, a 

102 string to `max_string` characters, each saying how much was left out, 

103 and anything more than `depth` levels below the object's own 

104 attributes to `...`. 

105 """ 

106 target = thing 

107 if not ( 

108 thing is None 

109 or isinstance(thing, _AS_THEY_ARE) 

110 or dataclasses.is_dataclass(thing) 

111 ): 

112 cls = type(type(thing).__qualname__, (_Struct,), {}) 

113 target = cls(_attributes(thing, private=private, methods=methods)) 

114 return Shown( 

115 target, max_length=max_items, max_string=max_string, max_depth=depth + 1 

116 ) 

117 

118 

119def _attributes(thing: Any, *, private: bool, methods: bool) -> list[tuple[str, Any]]: 

120 found: list[tuple[str, Any]] = [] 

121 for name in dir(thing): 

122 if name.startswith("__") or (name.startswith("_") and not private): 

123 continue 

124 try: 

125 attr = getattr(thing, name) 

126 except Exception as err: # noqa: BLE001 - a property can raise anything 

127 attr = _Text(f"<{type(err).__name__}: {err}>") 

128 if inspect.isroutine(attr) or inspect.isclass(attr): 

129 if not methods: 

130 continue 

131 attr = _Text( 

132 f"class {attr.__qualname__}" 

133 if inspect.isclass(attr) 

134 else f"def {name}{_signature(attr)}" 

135 ) 

136 found.append((name, attr)) 

137 return found 

138 

139 

140class _Text: 

141 """A value shown as this text, rather than as a quoted string.""" 

142 

143 def __init__(self, text: str) -> None: 

144 self.text = text 

145 

146 def __repr__(self) -> str: 

147 return self.text 

148 

149 

150def _is_summarisable(obj: Any) -> bool: 

151 """Classes and instances get the summary; modules, functions, strings 

152 (a topic or keyword to pydoc) and other primitives go to pydoc, whose 

153 page for those is short already.""" 

154 return not ( 

155 obj is None 

156 or isinstance(obj, (bool, int, float, complex, str, bytes)) 

157 or inspect.ismodule(obj) 

158 or inspect.isroutine(obj) 

159 ) 

160 

161 

162def _summary(thing: Any, width: int) -> Text: 

163 is_class = inspect.isclass(thing) 

164 cls = thing if is_class else type(thing) 

165 out = Text() 

166 

167 def section(title: str, lines: list[str]) -> None: 

168 if lines: 

169 out.append("\n") 

170 out.append(title + "\n", style="bold underline") 

171 out.append("\n".join(lines) + "\n") 

172 

173 kind = f"class {cls.__qualname__}" if is_class else f"{cls.__qualname__} object" 

174 out.append(f"Help on {kind} in module {cls.__module__}:\n", style="bold") 

175 doc = inspect.getdoc(cls) 

176 # A dataclass with no docstring of its own gets its signature as one. 

177 if doc and not doc.startswith(f"{cls.__name__}("): 177 ↛ 180line 177 didn't jump to line 180 because the condition on line 177 was always true

178 out.append(f"\n{doc}\n") 

179 

180 if is_class: 

181 section("Create:", [_wrap(f" {cls.__qualname__}{_signature(cls)}", width)]) 

182 else: 

183 call = getattr(cls, "__call__", None) # noqa: B004 - the method itself is wanted 

184 if inspect.isfunction(call): 

185 sig = _signature(call, drop_self=True) 

186 section("Call it:", [_wrap(f" {_name_of(thing)}{sig}", width)]) 

187 

188 members = { 

189 name: inspect.getattr_static(cls, name, None) 

190 for name in dir(cls) 

191 if not name.startswith("_") 

192 } 

193 section( 

194 "Methods:", 

195 [ 

196 _wrap(f" {name}{_signature(member, drop_self=True)}", width) 

197 for name, member in members.items() 

198 if inspect.isfunction(member) 

199 ], 

200 ) 

201 section( 

202 "Properties:", 

203 [ 

204 _described(name, inspect.getdoc(member), width) 

205 for name, member in members.items() 

206 if isinstance(member, property) 

207 ], 

208 ) 

209 if dataclasses.is_dataclass(cls): 209 ↛ 218line 209 didn't jump to line 218 because the condition on line 209 was always true

210 section( 

211 "Attributes:", 

212 [ 

213 _wrap(f" {field.name}: {_type_name(field.type)}", width) 

214 for field in dataclasses.fields(cls) 

215 if not field.name.startswith("_") 

216 ], 

217 ) 

218 out.append("\nhelp(thing, full=True) for Python's own full help page.") 

219 return out 

220 

221 

222def _name_of(thing: Any) -> str: 

223 """What an instance is bound as in the shell, if it's one of ours.""" 

224 return {"SqlTool": "sql"}.get(type(thing).__name__, type(thing).__name__) 

225 

226 

227def _described(name: str, doc: str | None, width: int) -> str: 

228 first = " ".join((doc or "").split("\n\n")[0].split()) 

229 return _wrap(f" {name}" + (f" - {first}" if first else ""), width) 

230 

231 

232def _wrap(line: str, width: int) -> str: 

233 return textwrap.fill( 

234 line, 

235 width=max(width, 20), 

236 subsequent_indent=" ", 

237 break_long_words=False, 

238 break_on_hyphens=False, 

239 ) 

240 

241 

242def _type_name(annotation: Any) -> str: 

243 return ( 

244 annotation 

245 if isinstance(annotation, str) 

246 else inspect.formatannotation(annotation) 

247 ) 

248 

249 

250def _signature(target: Any, *, drop_self: bool = False) -> str: 

251 try: 

252 sig = inspect.signature(target) 

253 except TypeError, ValueError: 

254 return "(...)" 

255 params = list(sig.parameters.values()) 

256 if drop_self and params and params[0].name == "self": 

257 sig = sig.replace(parameters=params[1:]) 

258 if sig.return_annotation in (None, "None", type(None)): 

259 sig = sig.replace(return_annotation=sig.empty) 

260 # Annotations are plain strings in a module using `from __future__ import 

261 # annotations` - shown as written, not as quoted strings. 

262 return sig.format(quote_annotation_strings=False)