Take the simple case of a Python function which evaluates a mathematical function:
def func(x, a, b, c):
"""Return the value of the quadratic function, ax^2 + bx + c."""
return a*x**2 + b*x + c
Suppose I want to "attach" some further information in the form of a function attribute. For example, the LaTeX representation. I know that thanks to PEP232 I can do this outside the function definition:
def func(x, a, b, c):
return a*x**2 + b*x + c
func.latex = r'$ax^2 + bx + c$'
but I'd like to do it within the function definition itself. If I write
def func(x, a, b, c):
func.latex = r'$ax^2 + bx + c$'
return a*x**2 + b*x + c
this certainly works, but only after I've called the func
for the first time (because Python is "lazy" in executing functions(?))
Is my only option to write a callable class?
class MyFunction:
def __init__(self, func, latex):
self.func = func
self.latex = latex
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
func = MyFunction(lambda x,a,b,c: a*x**2+b*x+c, r'$ax^2 + bx + c$')
Or is there a feature of the language that I'm overlooking to do this neatly?