I have a bunch of callback functions in a module. They all call some_func() with the first, say, couple of arguments always the same and derived from their own arguments, while other arguments vary. Like so:
from outer.space import some_func
def callback_A(param1, param2, param3):
...
some_func(param2+param1, param3, ..., ...)
...
def callback_B(param1, param2, param3, param4):
...
some_func(param2+param1, param3, ..., ...)
...
And it’s all over the code. And uglier than just param2+param1.
In C/C++, I’d just do a macro
#define S_F(a,b) some_func(param2+param1, param3, a, b)
and start using S_F inside callbacks instead of some_func. What can I do in Python?
You can use
functools.partialEdit:
Since you do not have these values in advance you can’t use
partialorlambda.You may be tempted to do this:
But as can you see it does not work. Why? Because when you define a function python saves the scope in which you defined it and uses it to resolve the
global/nonlocalvariables.If you had access to
some_funcit would be possible to do what you want by “hacking” the interpreter stack usinginspectbut this is not a robust nor elegant thing to do, so do not do that.What I’d do in your case is to simply rewrite the statement.
If you really want to avoid this, you can try something using
exec:But this is ugly.
If you use only positional arguments to your function you may do something more elegant such as:
But at this point you are just repeating a different text, and you lost much readability.
If you want to have preprocessing features in python you may try Python Preprocessing, even though, in your case, I’d rather just repeat the function calls.