[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Access function name from within a function

Hellmut Weber

3/12/2008 11:16:00 PM

Hi,
i would liek to define an error routine which print amongs other things
the name of the function from which it has been called.

Having tried

def foo():
print dir()

and all other ideas which came to my (rather python newbie) mind.

Googling too did not show me a possibility.

IOW what I'm looking for is:

def bar():
name = some_function(some-parameter)
print name

should print 'bar'

Any ideas appreciated

Hellmut

--
Dr. Hellmut Weber mail@hellmutweber.de
Degenfeldstraße 2 tel +49-89-3081172
D-80803 München-Schwabing mobil +49-172-8450321
please: No DOCs, no PPTs. why: tinyurl.com/cbgq

1 Answer

Steven D'Aprano

3/13/2008 12:23:00 AM

0

On Thu, 13 Mar 2008 00:16:13 +0100, Hellmut Weber wrote:

> Hi,
> i would liek to define an error routine which print amongs other things
> the name of the function from which it has been called.


You mean like Python exceptions already do?


>>> def broken():
.... x = 100 + 'foo'
.... return x
....
>>> broken()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in broken
TypeError: unsupported operand type(s) for +: 'int' and 'str'




> IOW what I'm looking for is:
>
> def bar():
> name = some_function(some-parameter)
> print name
>
> should print 'bar'

I'm guessing that what you want to do is something like this:

def bar():
do_calculation()
if error:
call_error_routine("something went wrong", magic_function())

where magic_function() knows the name of bar() is "bar".

But you already know the name of the function when you write it, so why
can't you do this?

def bar():
do_calculation()
if error:
call_error_routine("something went wrong", "bar")


Of course, this has the disadvantage that if you change the name of the
function bar(), you have to manually change the argument to your error
routine as well.


Another approach is this:

def bar():
import inspect
return inspect.getframeinfo(inspect.currentframe())[2]


but this should be considered the deepest Black Magic. I can make no
promises that it will work the way you expect it to work in all
circumstances. If you use this, you're elbow-deep in the Python internals.

Frankly, I think your approach of having an "error routine" is probably
the wrong approach, and you're better to use exceptions. But I could be
wrong.



--
Steven