
    wg8                        d Z ddlmZ ddlZddlmZmZ ddlZddlm	Z	 ddl
mZmZ ddlmZ ddlmZ dd	lmZmZmZ e	d
        Z G d d      Z G d d      Zd Zy)a&  Printing subsystem driver

SymPy's printing system works the following way: Any expression can be
passed to a designated Printer who then is responsible to return an
adequate representation of that expression.

**The basic concept is the following:**

1.  Let the object print itself if it knows how.
2.  Take the best fitting method defined in the printer.
3.  As fall-back use the emptyPrinter method for the printer.

Which Method is Responsible for Printing?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The whole printing process is started by calling ``.doprint(expr)`` on the printer
which you want to use. This method looks for an appropriate method which can
print the given expression in the given style that the printer defines.
While looking for the method, it follows these steps:

1.  **Let the object print itself if it knows how.**

    The printer looks for a specific method in every object. The name of that method
    depends on the specific printer and is defined under ``Printer.printmethod``.
    For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``.
    Look at the documentation of the printer that you want to use.
    The name of the method is specified there.

    This was the original way of doing printing in sympy. Every class had
    its own latex, mathml, str and repr methods, but it turned out that it
    is hard to produce a high quality printer, if all the methods are spread
    out that far. Therefore all printing code was combined into the different
    printers, which works great for built-in SymPy objects, but not that
    good for user defined classes where it is inconvenient to patch the
    printers.

2.  **Take the best fitting method defined in the printer.**

    The printer loops through expr classes (class + its bases), and tries
    to dispatch the work to ``_print_<EXPR_CLASS>``

    e.g., suppose we have the following class hierarchy::

            Basic
            |
            Atom
            |
            Number
            |
        Rational

    then, for ``expr=Rational(...)``, the Printer will try
    to call printer methods in the order as shown in the figure below::

        p._print(expr)
        |
        |-- p._print_Rational(expr)
        |
        |-- p._print_Number(expr)
        |
        |-- p._print_Atom(expr)
        |
        `-- p._print_Basic(expr)

    if ``._print_Rational`` method exists in the printer, then it is called,
    and the result is returned back. Otherwise, the printer tries to call
    ``._print_Number`` and so on.

3.  **As a fall-back use the emptyPrinter method for the printer.**

    As fall-back ``self.emptyPrinter`` will be called with the expression. If
    not defined in the Printer subclass this will be the same as ``str(expr)``.

.. _printer_example:

Example of Custom Printer
^^^^^^^^^^^^^^^^^^^^^^^^^

In the example below, we have a printer which prints the derivative of a function
in a shorter form.

.. code-block:: python

    from sympy.core.symbol import Symbol
    from sympy.printing.latex import LatexPrinter, print_latex
    from sympy.core.function import UndefinedFunction, Function


    class MyLatexPrinter(LatexPrinter):
        """Print derivative of a function of symbols in a shorter form.
        """
        def _print_Derivative(self, expr):
            function, *vars = expr.args
            if not isinstance(type(function), UndefinedFunction) or \
               not all(isinstance(i, Symbol) for i in vars):
                return super()._print_Derivative(expr)

            # If you want the printer to work correctly for nested
            # expressions then use self._print() instead of str() or latex().
            # See the example of nested modulo below in the custom printing
            # method section.
            return "{}_{{{}}}".format(
                self._print(Symbol(function.func.__name__)),
                            ''.join(self._print(i) for i in vars))


    def print_my_latex(expr):
        """ Most of the printers define their own wrappers for print().
        These wrappers usually take printer settings. Our printer does not have
        any settings.
        """
        print(MyLatexPrinter().doprint(expr))


    y = Symbol("y")
    x = Symbol("x")
    f = Function("f")
    expr = f(x, y).diff(x, y)

    # Print the expression using the normal latex printer and our custom
    # printer.
    print_latex(expr)
    print_my_latex(expr)

The output of the code above is::

    \frac{\partial^{2}}{\partial x\partial y}  f{\left(x,y \right)}
    f_{xy}

.. _printer_method_example:

Example of Custom Printing Method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In the example below, the latex printing of the modulo operator is modified.
This is done by overriding the method ``_latex`` of ``Mod``.

>>> from sympy import Symbol, Mod, Integer, print_latex

>>> # Always use printer._print()
>>> class ModOp(Mod):
...     def _latex(self, printer):
...         a, b = [printer._print(i) for i in self.args]
...         return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)

Comparing the output of our custom operator to the builtin one:

>>> x = Symbol('x')
>>> m = Symbol('m')
>>> print_latex(Mod(x, m))
x \bmod m
>>> print_latex(ModOp(x, m))
\operatorname{Mod}{\left(x, m\right)}

Common mistakes
~~~~~~~~~~~~~~~
It's important to always use ``self._print(obj)`` to print subcomponents of
an expression when customizing a printer. Mistakes include:

1.  Using ``self.doprint(obj)`` instead:

    >>> # This example does not work properly, as only the outermost call may use
    >>> # doprint.
    >>> class ModOpModeWrong(Mod):
    ...     def _latex(self, printer):
    ...         a, b = [printer.doprint(i) for i in self.args]
    ...         return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)

    This fails when the ``mode`` argument is passed to the printer:

    >>> print_latex(ModOp(x, m), mode='inline')  # ok
    $\operatorname{Mod}{\left(x, m\right)}$
    >>> print_latex(ModOpModeWrong(x, m), mode='inline')  # bad
    $\operatorname{Mod}{\left($x$, $m$\right)}$

2.  Using ``str(obj)`` instead:

    >>> class ModOpNestedWrong(Mod):
    ...     def _latex(self, printer):
    ...         a, b = [str(i) for i in self.args]
    ...         return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)

    This fails on nested objects:

    >>> # Nested modulo.
    >>> print_latex(ModOp(ModOp(x, m), Integer(7)))  # ok
    \operatorname{Mod}{\left(\operatorname{Mod}{\left(x, m\right)}, 7\right)}
    >>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7)))  # bad
    \operatorname{Mod}{\left(ModOpNestedWrong(x, m), 7\right)}

3.  Using ``LatexPrinter()._print(obj)`` instead.

    >>> from sympy.printing.latex import LatexPrinter
    >>> class ModOpSettingsWrong(Mod):
    ...     def _latex(self, printer):
    ...         a, b = [LatexPrinter()._print(i) for i in self.args]
    ...         return r"\operatorname{Mod}{\left(%s, %s\right)}" % (a, b)

    This causes all the settings to be discarded in the subobjects. As an
    example, the ``full_prec`` setting which shows floats to full precision is
    ignored:

    >>> from sympy import Float
    >>> print_latex(ModOp(Float(1) * x, m), full_prec=True)  # ok
    \operatorname{Mod}{\left(1.00000000000000 x, m\right)}
    >>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True)  # bad
    \operatorname{Mod}{\left(1.0 x, m\right)}

    )annotationsN)AnyType)contextmanager)
cmp_to_keyupdate_wrapper)Add)Basic)AppliedUndefUndefinedFunctionFunctionc              +     K   | j                   j                         }	 | j                   j                  |       d  || _         y # || _         w xY wwN)_contextcopyupdate)printerkwargsoriginals      [/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/printing/printer.pyprinter_contextr      sF     $$&H$'#8s   AA A	AAc                      e Zd ZU dZi Zded<   i Zded<   dZed        Z	ddZ
ed        Zed	        Zd
 ZddZd ZddZy)Printerz Generic printer

    Its job is to provide infrastructure for implementing new printers easily.

    If you want to define your custom Printer or your custom printing method
    for your custom class then see the example above: printer_example_ .
    zdict[str, Any]_global_settings_default_settingsNc                    | j                   j                         }| j                  j                         D ]  \  }}|| j                   v s|||<    |S r   )r   r   r   itemsclssettingskeyvals       r   _get_initial_settingszPrinter._get_initial_settings   sV    ((--/,,224 	$HCc+++ #	$     c                J   t         | _        | j                         | _        i | _        |s| j                  j                  |       t        | j                        t        | j                        kD  r-| j                  D ]  }|| j                  vst        d|z         d| _	        y )NzUnknown setting '%s'.r   )
str_strr#   	_settingsr   r   lenr   	TypeError_print_level)selfr    r!   s      r   __init__zPrinter.__init__  s    	335NN!!(+4>>"S)?)?%@@>> GC$"8"88'(?#(EFFG r$   c                X    |j                         D ]  \  }}|	|| j                  |<    y)z#Set system-wide printing settings. N)r   r   r   s       r   set_global_settingszPrinter.set_global_settings  s3     !( 	0HC,/$$S)	0r$   c                R    d| j                   v r| j                   d   S t        d      )NorderzNo order defined.)r(   AttributeErrorr,   s    r   r1   zPrinter.order  s)    dnn$>>'** !455r$   c                B    | j                  | j                  |            S )z7Returns printer's representation for expr (as a string))r'   _printr,   exprs     r   doprintzPrinter.doprint"  s    yyT*++r$   c                @   | xj                   dz  c_         	 | j                  rht        || j                        rRt        |t              rt        |t              s2 t        || j                        | fi || xj                   dz  c_         S t	        |      j                  t        v rj                  t              d t        v rj                  t              d t        v r2j                  t              }t        fdd| D              |d z   D ]@  }d|j                  z   }t        | |d      }|" ||fi |c | xj                   dz  c_         S  | j                  |      | xj                   dz  c_         S # | xj                   dz  c_         w xY w)a#  Internal dispatcher

        Tries the following concepts to print an expression:
            1. Let the object print itself if it knows how.
            2. Take the best fitting method defined in the printer.
            3. As fall-back use the emptyPrinter method for the printer.
           Nc              3     K   | ]=  }|j                   d    j                   k(  s|j                   j                  d      r| ? yw)r   BaseN)__name__endswith).0cclassess     r   	<genexpr>z!Printer._print.<locals>.<genexpr>D  s@       1aJJ'!*"5"55JJ''/ !"  1s   AA_print_)r+   printmethodhasattr
isinstancetype
issubclassr
   getattr__mro__r   indexr   r   tupler=   emptyPrinter)r,   r7   r   ir   printmethodnamerD   rA   s          @r   r5   zPrinter._print&  s    	Q 	# GD$2B2B$C"4.:dE3J:74)9)9:4J6J4 ") 4j((Gw&!'--"=">? G+!'--0A"B"CD 7"MM(+  172A;  1 13:12;?  7"+cll":%dOTB*&t6v66 "7 $$T*"D"s   AF B2F ?
F F Fc                    t        |      S r   )r&   r6   s     r   rM   zPrinter.emptyPrinterQ  s    4yr$   c                    |xs | j                   }|dk(  r7t        t        j                  |      t	        t
        j                              S |dk(  rt        |j                        S |j                  |      S )z4A compatibility function for ordering terms in Add. old)r!   none)r1   )
r1   sortedr	   	make_argsr   r
   _compare_prettylistargsas_ordered_terms)r,   r7   r1   s      r   _as_ordered_termszPrinter._as_ordered_termsT  sa    #E>#---:e>S>S3TUUf_		?"((u(55r$   r   )returnr&   )r=   
__module____qualname____doc__r   __annotations__r   rD   classmethodr#   r-   r/   propertyr1   r8   r5   rM   rZ    r$   r   r   r      sx     (*n)(*~*K $ 0 0 6 6,)#V	6r$   r   c                  6    e Zd ZdZddZd Zd Zedd       Zy)	_PrintFunctionz[
    Function wrapper to replace ``**settings`` in the signature with printer defaults
    c                   t        t        j                  |      j                  j	                               }|j                  d      j                  t        j                  j                  k(  sJ || _	        || _
        t        | |       y )N)rW   inspect	signature
parametersvaluespopkind	ParameterVAR_KEYWORD_PrintFunction__other_params_PrintFunction__print_clsr   )r,   f	print_clsparamss       r   r-   z_PrintFunction.__init__d  sh    g''*55<<>?zz"~""g&7&7&C&CCCC$$tQr$   c                .    | j                   j                  S r   )__wrapped__r]   r3   s    r   
__reduce__z_PrintFunction.__reduce__m  s     ,,,r$   c                &     | j                   |i |S r   )ru   )r,   rX   r   s      r   __call__z_PrintFunction.__call__s  s    t000r$   c                   | j                   j                         }t        j                  | j                  |j                         D cg c]5  \  }}t        j                  |t        j                  j                  |      7 c}}z   | j                  j                  j                  dt        j                  j                              S c c}}w )N)defaultr[   )ri   return_annotation)rp   r#   rg   	Signaturero   r   rm   KEYWORD_ONLYru   r_   getempty)r,   r    kvs       r   __signature__z_PrintFunction.__signature__v  s    ##99;  **$NN,.Aq !!!W%6%6%C%CQO.  #..>>BB8WM^M^MdMde
 	
.s   :C
N)rr   zType[Printer])r[   zinspect.Signature)	r=   r\   r]   r^   r-   rv   rx   ra   r   rb   r$   r   rd   rd   `  s*     -1 
 
r$   rd   c                      fd}|S )zJ A decorator to replace kwargs with the printer settings in __signature__ c                    t         j                  dk  r,t        | j                   dt        fd| j
                  i      }nt        } ||       S )N)   	   rd   r^   )sysversion_inforG   r]   rd   r^   )rq   r   rr   s     r   	decoratorz!print_function.<locals>.decorator  sN    f$ !..)8>:KiYZYbYbMcdC C1i  r$   rb   )rr   r   s   ` r   print_functionr     s    ! r$   )r^   
__future__r   r   typingr   r   rg   
contextlibr   	functoolsr   r   sympy.core.addr	   sympy.core.basicr
   sympy.core.functionr   r   r   r   r   rd   r   rb   r$   r   <module>r      s]   Pd # 
   % 0  " I I $ $r6 r6j
 
D
r$   