[Tutor] passing a function's name to another function

Remco Gerlich scarblac@pino.selwerd.nl
Tue, 28 Nov 2000 00:05:37 +0100

On Mon, Nov 27, 2000 at 11:38:43AM -0800, Mallett, Roger wrote:
> > I would like to pass the name of a function to another function.  However,
> > since the function's name may change I would like to pass a variable
> > rather than a hardcoded name.
> > 
> > I look in the help file and discovered a reference to an obsolete function
> > named codehack.  It apparently has been replaced by "func.func_name".  The
> > problem is I want the liberty to change the function's name without having
> > to change "func.func_name" as well.


> > For example, I have two functions, one named "Test" and one named
> > "NotImplementedYet".  I would like to have the freedom to change the name
> > of "Test" without having to change the argument it passes to
> > NotImplementedYet.  So, if I change the name of "Test" to "Apple" I don't
> > want to have to change "Test.func_name" to "Apple.func_name".
> > 
> > 
> > def NotImplementedYet(funcname):
> > 	print funcname, 'is Not Implemented Yet'
> > 
> > 
> > 
> > def Test():
> > 	NotImplementedYet(Test.func_name)  <<--it is the "Test" which
> > produces the maintenance issue

Ah right, I get you.

I think you need to raise some exception, catch it, and look at the current
stack frame (the information that is usually printed when an error occurs).
This leads to the following black magic:

import sys

def NotImplementedYet():
    raise "Dummy Error"
  except "Dummy Error":
    traceback = sys.exc_info()[2]
    lastframe = traceback.tb_frame.f_back
    name = lastframe.f_code.co_name
    print name, "is not implemented yet."

def SomeFunction():

I hope this works. You can get some more info like the line number too. It's
pretty ugly, but does what you want. Use at your own risk.

The other, much simpler solution is to just not implement the function
at all. Python will give an error when you try to call it ;-).

Remco Gerlich