Search code examples
sympy

Sympy no arguments in functions


I have some fairly long sympy expressions and I would like not to print the arguments of all these functions. I'm searching for a general solution because I have more than thirty functions in my equations.

Example:

a=sy.Function("a")
b=sy.Function("b")
expr=a(theta,phi)*b(zeta,theta)
sy.print_latex(expr,no_args=True)

a*b

sy.print_latex(expr)
a(theta,phi)*b(zeta,theta)

Thank you for helping.


Solution

  • You need to create a custom latex printer, and override the method responsible to create latex code of applied functions. Then, you need to inform init_printing that you want to use the newly created printer. Here is how:

    from sympy import *
    from sympy.printing.latex import LatexPrinter
    from sympy.core.function import AppliedUndef
    
    class MyLatexPrinter(LatexPrinter):
        """ Extended Latex printer with a new option:
    
        applied_no_args : bool
            wheter applied undefined function should be
            rendered with their arguments. Default to False.
        """
        def __init__(self, settings=None):
            self._default_settings.update({
                    "applied_no_args": False,
                }
            )
            super().__init__(settings)
            
        def _print_Function(self, expr, exp=None):
            if isinstance(expr, AppliedUndef) and self._settings["applied_no_args"]:
                if exp is None:
                    return expr.func.__name__
                else:
                    return r'%s^{%s}' % (expr.func.__name__, exp)
            return super()._print_Function(expr, exp)
    
    def my_latex(expr, **settings):
        return MyLatexPrinter(settings).doprint(expr)
    
    init_printing(latex_printer=my_latex, applied_no_args=True)
    x, y, z = symbols("x:z")
    f = Function("f")(x, y, z)
    f