how to get name of function from within function?

Steven Bethard steven.bethard at gmail.com
Sat Jun 4 09:16:02 CEST 2005


Christopher J. Bottaro wrote:
> 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"...=)

Something like this might work:

py> class C(object):
...     def func_a(self):
...         print "func_a"
...     def func_b_impl(self):
...         print "func_b"
...         raise Exception
...     def __getattr__(self, name):
...         func = getattr(self, '%s_impl' % name)
...         wrapped_func = self._impl_wrapper(func)
...         setattr(self, name, wrapped_func)
...         return wrapped_func
...     def _impl_wrapper(self, func):
...         def wrapper(*args, **kwargs):
...             try:
...                 return func(*args, **kwargs)
...             except:
...                 print "entered except"
...                 raise
...         return wrapper
...
py> c = C()
py> c.func_a()
func_a
py> c.func_b()
func_b
entered except
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
   File "<interactive input>", line 15, in wrapper
   File "<interactive input>", line 6, in func_b_impl
Exception

The idea here is that __getattr__ is called whenever the class doesn't 
have a particular function.  The __getattr__ method then tries to find a 
corresponding _impl function, wraps it with appropriate try/except code, 
and returns the wrapped function.

HTH,

STeVe



More information about the Python-list mailing list