printer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. """Printing subsystem driver
  2. SymPy's printing system works the following way: Any expression can be
  3. passed to a designated Printer who then is responsible to return an
  4. adequate representation of that expression.
  5. **The basic concept is the following:**
  6. 1. Let the object print itself if it knows how.
  7. 2. Take the best fitting method defined in the printer.
  8. 3. As fall-back use the emptyPrinter method for the printer.
  9. Which Method is Responsible for Printing?
  10. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  11. The whole printing process is started by calling ``.doprint(expr)`` on the printer
  12. which you want to use. This method looks for an appropriate method which can
  13. print the given expression in the given style that the printer defines.
  14. While looking for the method, it follows these steps:
  15. 1. **Let the object print itself if it knows how.**
  16. The printer looks for a specific method in every object. The name of that method
  17. depends on the specific printer and is defined under ``Printer.printmethod``.
  18. For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``.
  19. Look at the documentation of the printer that you want to use.
  20. The name of the method is specified there.
  21. This was the original way of doing printing in sympy. Every class had
  22. its own latex, mathml, str and repr methods, but it turned out that it
  23. is hard to produce a high quality printer, if all the methods are spread
  24. out that far. Therefore all printing code was combined into the different
  25. printers, which works great for built-in SymPy objects, but not that
  26. good for user defined classes where it is inconvenient to patch the
  27. printers.
  28. 2. **Take the best fitting method defined in the printer.**
  29. The printer loops through expr classes (class + its bases), and tries
  30. to dispatch the work to ``_print_<EXPR_CLASS>``
  31. e.g., suppose we have the following class hierarchy::
  32. Basic
  33. |
  34. Atom
  35. |
  36. Number
  37. |
  38. Rational
  39. then, for ``expr=Rational(...)``, the Printer will try
  40. to call printer methods in the order as shown in the figure below::
  41. p._print(expr)
  42. |
  43. |-- p._print_Rational(expr)
  44. |
  45. |-- p._print_Number(expr)
  46. |
  47. |-- p._print_Atom(expr)
  48. |
  49. `-- p._print_Basic(expr)
  50. if ``._print_Rational`` method exists in the printer, then it is called,
  51. and the result is returned back. Otherwise, the printer tries to call
  52. ``._print_Number`` and so on.
  53. 3. **As a fall-back use the emptyPrinter method for the printer.**
  54. As fall-back ``self.emptyPrinter`` will be called with the expression. If
  55. not defined in the Printer subclass this will be the same as ``str(expr)``.
  56. .. _printer_example:
  57. Example of Custom Printer
  58. ^^^^^^^^^^^^^^^^^^^^^^^^^
  59. In the example below, we have a printer which prints the derivative of a function
  60. in a shorter form.
  61. .. code-block:: python
  62. from sympy.core.symbol import Symbol
  63. from sympy.printing.latex import LatexPrinter, print_latex
  64. from sympy.core.function import UndefinedFunction, Function
  65. class MyLatexPrinter(LatexPrinter):
  66. \"\"\"Print derivative of a function of symbols in a shorter form.
  67. \"\"\"
  68. def _print_Derivative(self, expr):
  69. function, *vars = expr.args
  70. if not isinstance(type(function), UndefinedFunction) or \\
  71. not all(isinstance(i, Symbol) for i in vars):
  72. return super()._print_Derivative(expr)
  73. # If you want the printer to work correctly for nested
  74. # expressions then use self._print() instead of str() or latex().
  75. # See the example of nested modulo below in the custom printing
  76. # method section.
  77. return "{}_{{{}}}".format(
  78. self._print(Symbol(function.func.__name__)),
  79. ''.join(self._print(i) for i in vars))
  80. def print_my_latex(expr):
  81. \"\"\" Most of the printers define their own wrappers for print().
  82. These wrappers usually take printer settings. Our printer does not have
  83. any settings.
  84. \"\"\"
  85. print(MyLatexPrinter().doprint(expr))
  86. y = Symbol("y")
  87. x = Symbol("x")
  88. f = Function("f")
  89. expr = f(x, y).diff(x, y)
  90. # Print the expression using the normal latex printer and our custom
  91. # printer.
  92. print_latex(expr)
  93. print_my_latex(expr)
  94. The output of the code above is::
  95. \\frac{\\partial^{2}}{\\partial x\\partial y} f{\\left(x,y \\right)}
  96. f_{xy}
  97. .. _printer_method_example:
  98. Example of Custom Printing Method
  99. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  100. In the example below, the latex printing of the modulo operator is modified.
  101. This is done by overriding the method ``_latex`` of ``Mod``.
  102. >>> from sympy import Symbol, Mod, Integer, print_latex
  103. >>> # Always use printer._print()
  104. >>> class ModOp(Mod):
  105. ... def _latex(self, printer):
  106. ... a, b = [printer._print(i) for i in self.args]
  107. ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
  108. Comparing the output of our custom operator to the builtin one:
  109. >>> x = Symbol('x')
  110. >>> m = Symbol('m')
  111. >>> print_latex(Mod(x, m))
  112. x \\bmod m
  113. >>> print_latex(ModOp(x, m))
  114. \\operatorname{Mod}{\\left(x, m\\right)}
  115. Common mistakes
  116. ~~~~~~~~~~~~~~~
  117. It's important to always use ``self._print(obj)`` to print subcomponents of
  118. an expression when customizing a printer. Mistakes include:
  119. 1. Using ``self.doprint(obj)`` instead:
  120. >>> # This example does not work properly, as only the outermost call may use
  121. >>> # doprint.
  122. >>> class ModOpModeWrong(Mod):
  123. ... def _latex(self, printer):
  124. ... a, b = [printer.doprint(i) for i in self.args]
  125. ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
  126. This fails when the `mode` argument is passed to the printer:
  127. >>> print_latex(ModOp(x, m), mode='inline') # ok
  128. $\\operatorname{Mod}{\\left(x, m\\right)}$
  129. >>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad
  130. $\\operatorname{Mod}{\\left($x$, $m$\\right)}$
  131. 2. Using ``str(obj)`` instead:
  132. >>> class ModOpNestedWrong(Mod):
  133. ... def _latex(self, printer):
  134. ... a, b = [str(i) for i in self.args]
  135. ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
  136. This fails on nested objects:
  137. >>> # Nested modulo.
  138. >>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok
  139. \\operatorname{Mod}{\\left(\\operatorname{Mod}{\\left(x, m\\right)}, 7\\right)}
  140. >>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad
  141. \\operatorname{Mod}{\\left(ModOpNestedWrong(x, m), 7\\right)}
  142. 3. Using ``LatexPrinter()._print(obj)`` instead.
  143. >>> from sympy.printing.latex import LatexPrinter
  144. >>> class ModOpSettingsWrong(Mod):
  145. ... def _latex(self, printer):
  146. ... a, b = [LatexPrinter()._print(i) for i in self.args]
  147. ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b)
  148. This causes all the settings to be discarded in the subobjects. As an
  149. example, the ``full_prec`` setting which shows floats to full precision is
  150. ignored:
  151. >>> from sympy import Float
  152. >>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok
  153. \\operatorname{Mod}{\\left(1.00000000000000 x, m\\right)}
  154. >>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad
  155. \\operatorname{Mod}{\\left(1.0 x, m\\right)}
  156. """
  157. import sys
  158. from typing import Any, Dict as tDict, Type
  159. import inspect
  160. from contextlib import contextmanager
  161. from functools import cmp_to_key, update_wrapper
  162. from sympy.core.add import Add
  163. from sympy.core.basic import Basic
  164. from sympy.core.core import BasicMeta
  165. from sympy.core.function import AppliedUndef, UndefinedFunction, Function
  166. @contextmanager
  167. def printer_context(printer, **kwargs):
  168. original = printer._context.copy()
  169. try:
  170. printer._context.update(kwargs)
  171. yield
  172. finally:
  173. printer._context = original
  174. class Printer:
  175. """ Generic printer
  176. Its job is to provide infrastructure for implementing new printers easily.
  177. If you want to define your custom Printer or your custom printing method
  178. for your custom class then see the example above: printer_example_ .
  179. """
  180. _global_settings = {} # type: tDict[str, Any]
  181. _default_settings = {} # type: tDict[str, Any]
  182. printmethod = None # type: str
  183. @classmethod
  184. def _get_initial_settings(cls):
  185. settings = cls._default_settings.copy()
  186. for key, val in cls._global_settings.items():
  187. if key in cls._default_settings:
  188. settings[key] = val
  189. return settings
  190. def __init__(self, settings=None):
  191. self._str = str
  192. self._settings = self._get_initial_settings()
  193. self._context = dict() # mutable during printing
  194. if settings is not None:
  195. self._settings.update(settings)
  196. if len(self._settings) > len(self._default_settings):
  197. for key in self._settings:
  198. if key not in self._default_settings:
  199. raise TypeError("Unknown setting '%s'." % key)
  200. # _print_level is the number of times self._print() was recursively
  201. # called. See StrPrinter._print_Float() for an example of usage
  202. self._print_level = 0
  203. @classmethod
  204. def set_global_settings(cls, **settings):
  205. """Set system-wide printing settings. """
  206. for key, val in settings.items():
  207. if val is not None:
  208. cls._global_settings[key] = val
  209. @property
  210. def order(self):
  211. if 'order' in self._settings:
  212. return self._settings['order']
  213. else:
  214. raise AttributeError("No order defined.")
  215. def doprint(self, expr):
  216. """Returns printer's representation for expr (as a string)"""
  217. return self._str(self._print(expr))
  218. def _print(self, expr, **kwargs):
  219. """Internal dispatcher
  220. Tries the following concepts to print an expression:
  221. 1. Let the object print itself if it knows how.
  222. 2. Take the best fitting method defined in the printer.
  223. 3. As fall-back use the emptyPrinter method for the printer.
  224. """
  225. self._print_level += 1
  226. try:
  227. # If the printer defines a name for a printing method
  228. # (Printer.printmethod) and the object knows for itself how it
  229. # should be printed, use that method.
  230. if (self.printmethod and hasattr(expr, self.printmethod)
  231. and not isinstance(expr, BasicMeta)):
  232. return getattr(expr, self.printmethod)(self, **kwargs)
  233. # See if the class of expr is known, or if one of its super
  234. # classes is known, and use that print function
  235. # Exception: ignore the subclasses of Undefined, so that, e.g.,
  236. # Function('gamma') does not get dispatched to _print_gamma
  237. classes = type(expr).__mro__
  238. if AppliedUndef in classes:
  239. classes = classes[classes.index(AppliedUndef):]
  240. if UndefinedFunction in classes:
  241. classes = classes[classes.index(UndefinedFunction):]
  242. # Another exception: if someone subclasses a known function, e.g.,
  243. # gamma, and changes the name, then ignore _print_gamma
  244. if Function in classes:
  245. i = classes.index(Function)
  246. classes = tuple(c for c in classes[:i] if \
  247. c.__name__ == classes[0].__name__ or \
  248. c.__name__.endswith("Base")) + classes[i:]
  249. for cls in classes:
  250. printmethodname = '_print_' + cls.__name__
  251. printmethod = getattr(self, printmethodname, None)
  252. if printmethod is not None:
  253. return printmethod(expr, **kwargs)
  254. # Unknown object, fall back to the emptyPrinter.
  255. return self.emptyPrinter(expr)
  256. finally:
  257. self._print_level -= 1
  258. def emptyPrinter(self, expr):
  259. return str(expr)
  260. def _as_ordered_terms(self, expr, order=None):
  261. """A compatibility function for ordering terms in Add. """
  262. order = order or self.order
  263. if order == 'old':
  264. return sorted(Add.make_args(expr), key=cmp_to_key(Basic._compare_pretty))
  265. elif order == 'none':
  266. return list(expr.args)
  267. else:
  268. return expr.as_ordered_terms(order=order)
  269. class _PrintFunction:
  270. """
  271. Function wrapper to replace ``**settings`` in the signature with printer defaults
  272. """
  273. def __init__(self, f, print_cls: Type[Printer]):
  274. # find all the non-setting arguments
  275. params = list(inspect.signature(f).parameters.values())
  276. assert params.pop(-1).kind == inspect.Parameter.VAR_KEYWORD
  277. self.__other_params = params
  278. self.__print_cls = print_cls
  279. update_wrapper(self, f)
  280. def __reduce__(self):
  281. # Since this is used as a decorator, it replaces the original function.
  282. # The default pickling will try to pickle self.__wrapped__ and fail
  283. # because the wrapped function can't be retrieved by name.
  284. return self.__wrapped__.__qualname__
  285. def __call__(self, *args, **kwargs):
  286. return self.__wrapped__(*args, **kwargs)
  287. @property
  288. def __signature__(self) -> inspect.Signature:
  289. settings = self.__print_cls._get_initial_settings()
  290. return inspect.Signature(
  291. parameters=self.__other_params + [
  292. inspect.Parameter(k, inspect.Parameter.KEYWORD_ONLY, default=v)
  293. for k, v in settings.items()
  294. ],
  295. return_annotation=self.__wrapped__.__annotations__.get('return', inspect.Signature.empty) # type:ignore
  296. )
  297. def print_function(print_cls):
  298. """ A decorator to replace kwargs with the printer settings in __signature__ """
  299. def decorator(f):
  300. if sys.version_info < (3, 9):
  301. # We have to create a subclass so that `help` actually shows the docstring in older Python versions.
  302. # IPython and Sphinx do not need this, only a raw Python console.
  303. cls = type(f'{f.__qualname__}_PrintFunction', (_PrintFunction,), dict(__doc__=f.__doc__))
  304. else:
  305. cls = _PrintFunction
  306. return cls(f, print_cls)
  307. return decorator