how to get name of function from within function?

Christopher J. Bottaro cjbottaro at alumni.cs.utexas.edu
Sat Jun 4 14:16:54 EDT 2005


Steven Bethard wrote:

...snip... 

> 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,

Yes, it does!  Thats perfect, and it works with Python 2.3 (which I'm
using).  Thank you very much.

> STeVe

-- C




More information about the Python-list mailing list