Hard Python question
I am trying to do something which is, I think, pretty cool, in python.
However, I like showing things working, and I am having troubles with the last final step on what I am trying to achieve.
Since I know a few better python programmers read this...
Suppose I have this:
def fun(self,x): pass class C: pass C.a=fun C.b=fun
What code should be in fun() so that it figures out if it has been called as C.a or as C.b?
I am thinking something like reading the higher step in a backtrace, but I don't know enough python to figure out how to do that.
I don't think this is possible, as the "method" name you are using to call the function doesn't make it on to the call stack. You can get stack frames using sys._getframe, but I doubt the method name will appear in there (it's just a key/value pair in the class dict). If you really must get this kind of info you're better off doing something like:
def fun(self, callname): blah
C.a = lambda self: fun(self, 'a')
C.b = lambda self: fun(self, 'b')
but it really must be asked what you're trying to do :)
Looks like it *is* feasible!
Thanks taj for that _getframe , because googling for it just lead me here:
Blah, I only get a '?' as function name :-P
Have a look at my extremely simplistic interface to the DCOP command line app, it does something very similar: