Access function name from within a function

H

Hellmut Weber

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
 
S

Steven D'Aprano

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?

.... x = 100 + 'foo'
.... return x
....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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top