Here is what I want to do:
class demo(object):
def a(self):
pass
def b(self, param=self.a): #I tried demo.a as well after making a static
param()
The problem is apparently that one can’t access the class in the function declaration line.
Is there a way to add a prototype like in c(++)?
At the moment I use a ugly workarround:
def b(self, param=True): #my real function shall be able to use None, to skip the function call
if param == True:
param = self.a
if param != None: #This explainds why I can't take None as default,
#for param, I jsut needed something as default which was
#neither none or a callable function (don't want to force the user to create dummy lambdas)
param()
So is it possible to achieve something like described in the top part without this ugly workarround? Note bene: I am bound to Jython which is approximately python 2.5 (I know there is 2.7 but I can’t upgrade)
I’ll answer this question again, contradicting my earlier answer:
Short answer: YES! (sort of)
With the help of a method decorator, this is possible. The code is long and somewhat ugly, but the usage is short and simple.
The problem was that we can only use unbound methods as default arguments. Well, what if we create a wrapping function — a decorator — which binds the arguments before calling the real function?
First we create a helper class that can perform this task.
So instances of
MethodBinderare associated with a method (or rather a function that will become a method).MethodBinders methodset_defaultsmay be given the arguments used to call the associated method, and it will bind any unbound method of theselfof the associated method and return a kwargs dict that may be used to call the associated method.Now we can create a decorator using this class:
Now that we’ve put the uglyness behind us, let’s show the simple and pretty usage:
This recipe uses a rather new addition to python,
getcallargsfrominspect. It’s available only in newer versions of python2.7 and 3.1.