Access function name from within a function

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Mar 12 20:23:13 EDT 2008


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



More information about the Python-list mailing list