_pprint.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. """This module contains the _EstimatorPrettyPrinter class used in
  2. BaseEstimator.__repr__ for pretty-printing estimators"""
  3. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
  4. # 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Python Software Foundation;
  5. # All Rights Reserved
  6. # Authors: Fred L. Drake, Jr. <fdrake@acm.org> (built-in CPython pprint module)
  7. # Nicolas Hug (scikit-learn specific changes)
  8. # License: PSF License version 2 (see below)
  9. # PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
  10. # --------------------------------------------
  11. # 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"),
  12. # and the Individual or Organization ("Licensee") accessing and otherwise
  13. # using this software ("Python") in source or binary form and its associated
  14. # documentation.
  15. # 2. Subject to the terms and conditions of this License Agreement, PSF hereby
  16. # grants Licensee a nonexclusive, royalty-free, world-wide license to
  17. # reproduce, analyze, test, perform and/or display publicly, prepare
  18. # derivative works, distribute, and otherwise use Python alone or in any
  19. # derivative version, provided, however, that PSF's License Agreement and
  20. # PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004,
  21. # 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016,
  22. # 2017, 2018 Python Software Foundation; All Rights Reserved" are retained in
  23. # Python alone or in any derivative version prepared by Licensee.
  24. # 3. In the event Licensee prepares a derivative work that is based on or
  25. # incorporates Python or any part thereof, and wants to make the derivative
  26. # work available to others as provided herein, then Licensee hereby agrees to
  27. # include in any such work a brief summary of the changes made to Python.
  28. # 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES
  29. # NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT
  30. # NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF
  31. # MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
  32. # PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.
  33. # 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY
  34. # INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
  35. # MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE
  36. # THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
  37. # 6. This License Agreement will automatically terminate upon a material
  38. # breach of its terms and conditions.
  39. # 7. Nothing in this License Agreement shall be deemed to create any
  40. # relationship of agency, partnership, or joint venture between PSF and
  41. # Licensee. This License Agreement does not grant permission to use PSF
  42. # trademarks or trade name in a trademark sense to endorse or promote products
  43. # or services of Licensee, or any third party.
  44. # 8. By copying, installing or otherwise using Python, Licensee agrees to be
  45. # bound by the terms and conditions of this License Agreement.
  46. # Brief summary of changes to original code:
  47. # - "compact" parameter is supported for dicts, not just lists or tuples
  48. # - estimators have a custom handler, they're not just treated as objects
  49. # - long sequences (lists, tuples, dict items) with more than N elements are
  50. # shortened using ellipsis (', ...') at the end.
  51. import inspect
  52. import pprint
  53. from collections import OrderedDict
  54. from .._config import get_config
  55. from ..base import BaseEstimator
  56. from . import is_scalar_nan
  57. class KeyValTuple(tuple):
  58. """Dummy class for correctly rendering key-value tuples from dicts."""
  59. def __repr__(self):
  60. # needed for _dispatch[tuple.__repr__] not to be overridden
  61. return super().__repr__()
  62. class KeyValTupleParam(KeyValTuple):
  63. """Dummy class for correctly rendering key-value tuples from parameters."""
  64. pass
  65. def _changed_params(estimator):
  66. """Return dict (param_name: value) of parameters that were given to
  67. estimator with non-default values."""
  68. params = estimator.get_params(deep=False)
  69. init_func = getattr(estimator.__init__, "deprecated_original", estimator.__init__)
  70. init_params = inspect.signature(init_func).parameters
  71. init_params = {name: param.default for name, param in init_params.items()}
  72. def has_changed(k, v):
  73. if k not in init_params: # happens if k is part of a **kwargs
  74. return True
  75. if init_params[k] == inspect._empty: # k has no default value
  76. return True
  77. # try to avoid calling repr on nested estimators
  78. if isinstance(v, BaseEstimator) and v.__class__ != init_params[k].__class__:
  79. return True
  80. # Use repr as a last resort. It may be expensive.
  81. if repr(v) != repr(init_params[k]) and not (
  82. is_scalar_nan(init_params[k]) and is_scalar_nan(v)
  83. ):
  84. return True
  85. return False
  86. return {k: v for k, v in params.items() if has_changed(k, v)}
  87. class _EstimatorPrettyPrinter(pprint.PrettyPrinter):
  88. """Pretty Printer class for estimator objects.
  89. This extends the pprint.PrettyPrinter class, because:
  90. - we need estimators to be printed with their parameters, e.g.
  91. Estimator(param1=value1, ...) which is not supported by default.
  92. - the 'compact' parameter of PrettyPrinter is ignored for dicts, which
  93. may lead to very long representations that we want to avoid.
  94. Quick overview of pprint.PrettyPrinter (see also
  95. https://stackoverflow.com/questions/49565047/pprint-with-hex-numbers):
  96. - the entry point is the _format() method which calls format() (overridden
  97. here)
  98. - format() directly calls _safe_repr() for a first try at rendering the
  99. object
  100. - _safe_repr formats the whole object recursively, only calling itself,
  101. not caring about line length or anything
  102. - back to _format(), if the output string is too long, _format() then calls
  103. the appropriate _pprint_TYPE() method (e.g. _pprint_list()) depending on
  104. the type of the object. This where the line length and the compact
  105. parameters are taken into account.
  106. - those _pprint_TYPE() methods will internally use the format() method for
  107. rendering the nested objects of an object (e.g. the elements of a list)
  108. In the end, everything has to be implemented twice: in _safe_repr and in
  109. the custom _pprint_TYPE methods. Unfortunately PrettyPrinter is really not
  110. straightforward to extend (especially when we want a compact output), so
  111. the code is a bit convoluted.
  112. This class overrides:
  113. - format() to support the changed_only parameter
  114. - _safe_repr to support printing of estimators (for when they fit on a
  115. single line)
  116. - _format_dict_items so that dict are correctly 'compacted'
  117. - _format_items so that ellipsis is used on long lists and tuples
  118. When estimators cannot be printed on a single line, the builtin _format()
  119. will call _pprint_estimator() because it was registered to do so (see
  120. _dispatch[BaseEstimator.__repr__] = _pprint_estimator).
  121. both _format_dict_items() and _pprint_estimator() use the
  122. _format_params_or_dict_items() method that will format parameters and
  123. key-value pairs respecting the compact parameter. This method needs another
  124. subroutine _pprint_key_val_tuple() used when a parameter or a key-value
  125. pair is too long to fit on a single line. This subroutine is called in
  126. _format() and is registered as well in the _dispatch dict (just like
  127. _pprint_estimator). We had to create the two classes KeyValTuple and
  128. KeyValTupleParam for this.
  129. """
  130. def __init__(
  131. self,
  132. indent=1,
  133. width=80,
  134. depth=None,
  135. stream=None,
  136. *,
  137. compact=False,
  138. indent_at_name=True,
  139. n_max_elements_to_show=None,
  140. ):
  141. super().__init__(indent, width, depth, stream, compact=compact)
  142. self._indent_at_name = indent_at_name
  143. if self._indent_at_name:
  144. self._indent_per_level = 1 # ignore indent param
  145. self._changed_only = get_config()["print_changed_only"]
  146. # Max number of elements in a list, dict, tuple until we start using
  147. # ellipsis. This also affects the number of arguments of an estimators
  148. # (they are treated as dicts)
  149. self.n_max_elements_to_show = n_max_elements_to_show
  150. def format(self, object, context, maxlevels, level):
  151. return _safe_repr(
  152. object, context, maxlevels, level, changed_only=self._changed_only
  153. )
  154. def _pprint_estimator(self, object, stream, indent, allowance, context, level):
  155. stream.write(object.__class__.__name__ + "(")
  156. if self._indent_at_name:
  157. indent += len(object.__class__.__name__)
  158. if self._changed_only:
  159. params = _changed_params(object)
  160. else:
  161. params = object.get_params(deep=False)
  162. params = OrderedDict((name, val) for (name, val) in sorted(params.items()))
  163. self._format_params(
  164. params.items(), stream, indent, allowance + 1, context, level
  165. )
  166. stream.write(")")
  167. def _format_dict_items(self, items, stream, indent, allowance, context, level):
  168. return self._format_params_or_dict_items(
  169. items, stream, indent, allowance, context, level, is_dict=True
  170. )
  171. def _format_params(self, items, stream, indent, allowance, context, level):
  172. return self._format_params_or_dict_items(
  173. items, stream, indent, allowance, context, level, is_dict=False
  174. )
  175. def _format_params_or_dict_items(
  176. self, object, stream, indent, allowance, context, level, is_dict
  177. ):
  178. """Format dict items or parameters respecting the compact=True
  179. parameter. For some reason, the builtin rendering of dict items doesn't
  180. respect compact=True and will use one line per key-value if all cannot
  181. fit in a single line.
  182. Dict items will be rendered as <'key': value> while params will be
  183. rendered as <key=value>. The implementation is mostly copy/pasting from
  184. the builtin _format_items().
  185. This also adds ellipsis if the number of items is greater than
  186. self.n_max_elements_to_show.
  187. """
  188. write = stream.write
  189. indent += self._indent_per_level
  190. delimnl = ",\n" + " " * indent
  191. delim = ""
  192. width = max_width = self._width - indent + 1
  193. it = iter(object)
  194. try:
  195. next_ent = next(it)
  196. except StopIteration:
  197. return
  198. last = False
  199. n_items = 0
  200. while not last:
  201. if n_items == self.n_max_elements_to_show:
  202. write(", ...")
  203. break
  204. n_items += 1
  205. ent = next_ent
  206. try:
  207. next_ent = next(it)
  208. except StopIteration:
  209. last = True
  210. max_width -= allowance
  211. width -= allowance
  212. if self._compact:
  213. k, v = ent
  214. krepr = self._repr(k, context, level)
  215. vrepr = self._repr(v, context, level)
  216. if not is_dict:
  217. krepr = krepr.strip("'")
  218. middle = ": " if is_dict else "="
  219. rep = krepr + middle + vrepr
  220. w = len(rep) + 2
  221. if width < w:
  222. width = max_width
  223. if delim:
  224. delim = delimnl
  225. if width >= w:
  226. width -= w
  227. write(delim)
  228. delim = ", "
  229. write(rep)
  230. continue
  231. write(delim)
  232. delim = delimnl
  233. class_ = KeyValTuple if is_dict else KeyValTupleParam
  234. self._format(
  235. class_(ent), stream, indent, allowance if last else 1, context, level
  236. )
  237. def _format_items(self, items, stream, indent, allowance, context, level):
  238. """Format the items of an iterable (list, tuple...). Same as the
  239. built-in _format_items, with support for ellipsis if the number of
  240. elements is greater than self.n_max_elements_to_show.
  241. """
  242. write = stream.write
  243. indent += self._indent_per_level
  244. if self._indent_per_level > 1:
  245. write((self._indent_per_level - 1) * " ")
  246. delimnl = ",\n" + " " * indent
  247. delim = ""
  248. width = max_width = self._width - indent + 1
  249. it = iter(items)
  250. try:
  251. next_ent = next(it)
  252. except StopIteration:
  253. return
  254. last = False
  255. n_items = 0
  256. while not last:
  257. if n_items == self.n_max_elements_to_show:
  258. write(", ...")
  259. break
  260. n_items += 1
  261. ent = next_ent
  262. try:
  263. next_ent = next(it)
  264. except StopIteration:
  265. last = True
  266. max_width -= allowance
  267. width -= allowance
  268. if self._compact:
  269. rep = self._repr(ent, context, level)
  270. w = len(rep) + 2
  271. if width < w:
  272. width = max_width
  273. if delim:
  274. delim = delimnl
  275. if width >= w:
  276. width -= w
  277. write(delim)
  278. delim = ", "
  279. write(rep)
  280. continue
  281. write(delim)
  282. delim = delimnl
  283. self._format(ent, stream, indent, allowance if last else 1, context, level)
  284. def _pprint_key_val_tuple(self, object, stream, indent, allowance, context, level):
  285. """Pretty printing for key-value tuples from dict or parameters."""
  286. k, v = object
  287. rep = self._repr(k, context, level)
  288. if isinstance(object, KeyValTupleParam):
  289. rep = rep.strip("'")
  290. middle = "="
  291. else:
  292. middle = ": "
  293. stream.write(rep)
  294. stream.write(middle)
  295. self._format(
  296. v, stream, indent + len(rep) + len(middle), allowance, context, level
  297. )
  298. # Note: need to copy _dispatch to prevent instances of the builtin
  299. # PrettyPrinter class to call methods of _EstimatorPrettyPrinter (see issue
  300. # 12906)
  301. # mypy error: "Type[PrettyPrinter]" has no attribute "_dispatch"
  302. _dispatch = pprint.PrettyPrinter._dispatch.copy() # type: ignore
  303. _dispatch[BaseEstimator.__repr__] = _pprint_estimator
  304. _dispatch[KeyValTuple.__repr__] = _pprint_key_val_tuple
  305. def _safe_repr(object, context, maxlevels, level, changed_only=False):
  306. """Same as the builtin _safe_repr, with added support for Estimator
  307. objects."""
  308. typ = type(object)
  309. if typ in pprint._builtin_scalars:
  310. return repr(object), True, False
  311. r = getattr(typ, "__repr__", None)
  312. if issubclass(typ, dict) and r is dict.__repr__:
  313. if not object:
  314. return "{}", True, False
  315. objid = id(object)
  316. if maxlevels and level >= maxlevels:
  317. return "{...}", False, objid in context
  318. if objid in context:
  319. return pprint._recursion(object), False, True
  320. context[objid] = 1
  321. readable = True
  322. recursive = False
  323. components = []
  324. append = components.append
  325. level += 1
  326. saferepr = _safe_repr
  327. items = sorted(object.items(), key=pprint._safe_tuple)
  328. for k, v in items:
  329. krepr, kreadable, krecur = saferepr(
  330. k, context, maxlevels, level, changed_only=changed_only
  331. )
  332. vrepr, vreadable, vrecur = saferepr(
  333. v, context, maxlevels, level, changed_only=changed_only
  334. )
  335. append("%s: %s" % (krepr, vrepr))
  336. readable = readable and kreadable and vreadable
  337. if krecur or vrecur:
  338. recursive = True
  339. del context[objid]
  340. return "{%s}" % ", ".join(components), readable, recursive
  341. if (issubclass(typ, list) and r is list.__repr__) or (
  342. issubclass(typ, tuple) and r is tuple.__repr__
  343. ):
  344. if issubclass(typ, list):
  345. if not object:
  346. return "[]", True, False
  347. format = "[%s]"
  348. elif len(object) == 1:
  349. format = "(%s,)"
  350. else:
  351. if not object:
  352. return "()", True, False
  353. format = "(%s)"
  354. objid = id(object)
  355. if maxlevels and level >= maxlevels:
  356. return format % "...", False, objid in context
  357. if objid in context:
  358. return pprint._recursion(object), False, True
  359. context[objid] = 1
  360. readable = True
  361. recursive = False
  362. components = []
  363. append = components.append
  364. level += 1
  365. for o in object:
  366. orepr, oreadable, orecur = _safe_repr(
  367. o, context, maxlevels, level, changed_only=changed_only
  368. )
  369. append(orepr)
  370. if not oreadable:
  371. readable = False
  372. if orecur:
  373. recursive = True
  374. del context[objid]
  375. return format % ", ".join(components), readable, recursive
  376. if issubclass(typ, BaseEstimator):
  377. objid = id(object)
  378. if maxlevels and level >= maxlevels:
  379. return "{...}", False, objid in context
  380. if objid in context:
  381. return pprint._recursion(object), False, True
  382. context[objid] = 1
  383. readable = True
  384. recursive = False
  385. if changed_only:
  386. params = _changed_params(object)
  387. else:
  388. params = object.get_params(deep=False)
  389. components = []
  390. append = components.append
  391. level += 1
  392. saferepr = _safe_repr
  393. items = sorted(params.items(), key=pprint._safe_tuple)
  394. for k, v in items:
  395. krepr, kreadable, krecur = saferepr(
  396. k, context, maxlevels, level, changed_only=changed_only
  397. )
  398. vrepr, vreadable, vrecur = saferepr(
  399. v, context, maxlevels, level, changed_only=changed_only
  400. )
  401. append("%s=%s" % (krepr.strip("'"), vrepr))
  402. readable = readable and kreadable and vreadable
  403. if krecur or vrecur:
  404. recursive = True
  405. del context[objid]
  406. return ("%s(%s)" % (typ.__name__, ", ".join(components)), readable, recursive)
  407. rep = repr(object)
  408. return rep, (rep and not rep.startswith("<")), False