how to get name of function from within function?

Christopher J. Bottaro cjbottaro at alumni.cs.utexas.edu
Sat Jun 4 02:01:15 EDT 2005


Steven Bethard wrote:
[...snip...]
> Yes, has's suggestion is probably the right way to go here.  I'm still
> uncertain as to your exact setup here.  Are the functions you need to
> wrap in a list you have?  Are they imported from another module?  A
> short clip of your current code and what you want it to do would help.

But I want to avoid having to write each wrapper myself.  As it is now, when
I want to add a public method to my class named myFunc, I first write
myFunc which is a wrapper to the implementation:

def myFunc(self):
  try: self.myFuncIMPL()
  except: # error handling code

def myFuncIMPL(self):
  # do the real stuff here, no need to worry about error handling stuff
  # cuz its done in the wrapper

I guess I'm just lazy, but I don't want to write the wrapper func for each
new func I want to add.  I want it done automatically.

> I don't know.  What does PHP's __call() do?  I don't know PHP, and it
> wasn't in the online manual http://www.php.net/docs.php.

http://www.php.net/manual/en/language.oop5.overloading.php

I haven't tried it yet, but this is what I would do with __call():

function __call($name, $args)  {
  $name .= 'IMPL';
  try { $this->$name($args); }
  except { # error handling; }
}

function funcA()  {
  # do something
}

function funcBIMPL($a, $b)  {
  # do something
}

So I imagine it would work like this:

$obj = new MyClass();
$obj->funcA();  # actually calls funcA because the function
                # exists in the class
$obj->funcB($a, $b);  # funcB doesn't exist, so __call() gets called with
                      # args 'funcB', array($a, $b)
# so inside __call(), we append 'IMPL' to $name, then invoke
# $this->funcBIMPL($a, $b)

Using this setup, when I want to add a new function called mySuperFunc(), I
merely have to define mySuperFuncIMPL() and magically the wrapper is "made
for me"...=)

Thanks for the help and ideas!




More information about the Python-list mailing list