_print_helpers.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """
  2. Base class to provide str and repr hooks that `init_printing` can overwrite.
  3. This is exposed publicly in the `printing.defaults` module,
  4. but cannot be defined there without causing circular imports.
  5. """
  6. class Printable:
  7. """
  8. The default implementation of printing for SymPy classes.
  9. This implements a hack that allows us to print elements of built-in
  10. Python containers in a readable way. Natively Python uses ``repr()``
  11. even if ``str()`` was explicitly requested. Mix in this trait into
  12. a class to get proper default printing.
  13. This also adds support for LaTeX printing in jupyter notebooks.
  14. """
  15. # Since this class is used as a mixin we set empty slots. That means that
  16. # instances of any subclasses that use slots will not need to have a
  17. # __dict__.
  18. __slots__ = ()
  19. # Note, we always use the default ordering (lex) in __str__ and __repr__,
  20. # regardless of the global setting. See issue 5487.
  21. def __str__(self):
  22. from sympy.printing.str import sstr
  23. return sstr(self, order=None)
  24. __repr__ = __str__
  25. def _repr_disabled(self):
  26. """
  27. No-op repr function used to disable jupyter display hooks.
  28. When :func:`sympy.init_printing` is used to disable certain display
  29. formats, this function is copied into the appropriate ``_repr_*_``
  30. attributes.
  31. While we could just set the attributes to `None``, doing it this way
  32. allows derived classes to call `super()`.
  33. """
  34. return None
  35. # We don't implement _repr_png_ here because it would add a large amount of
  36. # data to any notebook containing SymPy expressions, without adding
  37. # anything useful to the notebook. It can still enabled manually, e.g.,
  38. # for the qtconsole, with init_printing().
  39. _repr_png_ = _repr_disabled
  40. _repr_svg_ = _repr_disabled
  41. def _repr_latex_(self):
  42. """
  43. IPython/Jupyter LaTeX printing
  44. To change the behavior of this (e.g., pass in some settings to LaTeX),
  45. use init_printing(). init_printing() will also enable LaTeX printing
  46. for built in numeric types like ints and container types that contain
  47. SymPy objects, like lists and dictionaries of expressions.
  48. """
  49. from sympy.printing.latex import latex
  50. s = latex(self, mode='plain')
  51. return "$\\displaystyle %s$" % s