Skip to main content

Ralsina.Me — Roberto Alsina's website

Hard Python question

I am try­ing to do some­thing which is, I think, pret­ty cool, in python.

How­ev­er, I like show­ing things work­ing, and I am hav­ing trou­bles with the last fi­nal step on what I am try­ing to achieve.

Since I know a few bet­ter python pro­gram­mers read this...

Sup­pose 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 fig­ures out if it has been called as C.a or as C.b?

I am think­ing some­thing like read­ing the high­er step in a back­trace, but I don't know enough python to fig­ure out how to do that.

taj / 2006-04-03 06:57:

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 :)

Roberto Alsina / 2006-04-03 06:58:

Blah, I only get a '?' as function name :-P

Roberto Alsina / 2006-04-03 06:58:

Looks like it *is* feasible!



Thanks taj for that _getframe , because googling for it just lead me here:



http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062

taj / 2006-04-03 06:59:

Have a look at my extremely simplistic interface to the DCOP command line app, it does something very similar:



http://sirtaj.net/projects/pycdcop/dcop.py


Contents © 2000-2024 Roberto Alsina