how to get name of function from within function?
Kent Johnson
kent37 at tds.net
Sat Jun 4 05:55:18 EDT 2005
Christopher J. Bottaro wrote:
> 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.
You can do this almost automatically with a decorator:
def in_try(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
print "entered except"
raise
return wrapper
class C(object):
@in_try
def func_a(self):
print "func_a"
@in_try
def func_b(self):
print "func_b"
raise Exception
You could probably create a metaclass to apply the wrappers automatically but I like having it explicit as above.
Kent
More information about the Python-list
mailing list