how to get name of function from within function?

Steven Bethard steven.bethard at gmail.com
Fri Jun 3 20:52:16 EDT 2005


Christopher J. Bottaro wrote:
> Basically I want to wrap every function in try/except automatically.
[snip]
> every function (err, method) is enclosed in the exact
> same try/except error handling code.  Everytime I make a new function, I
> copy/paste that try/catch block.

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.

For example, if they are the only thing another module contains, you can 
use has's wrapFunction function and do something like:

import functionmodule

for name in dir(functionmodule):
     if not name.startswith('_'):
         func = wrapFunction(getattr(functionmodule, name))
         setattr(functionmodule, name, func)

> Is there something like PHP's __call() method in Python?

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.

>>>Also, is there a way to turn normal positional args into a tuple without
>>>using *?  Like this:
>>>
>>>def f(a, b, c):
>>>  print get_args_as_tuple()
>>>
>>>
>>>>>>f(1, 2, 3)
>>>
>>>(1, 2, 3)
>>
>>Um...
>>
>>py> def f(a, b, c):
>>...     print (a, b, c)
>>...
>>py> f(1, 2, 3)
>>(1, 2, 3)
>>
>>?
> 
> In your method, if the name and/or number of positional arguments changes,
> the body of the function must change.  I want to avoid that.

But if the name and/or number of positional arguments changes, you're 
already changing the function definition.  What's the real use case 
here?  Are you really just printing them?  Or are you doing something else?

STeVe



More information about the Python-list mailing list