getting the function name

B

beliavsky

Is there a way in Python to print the name of the function one is
currently in?
The code

def foo():
debug = True
if (debug):
print "entered",__name__

x = foo()

outputs "entered __main__"

I want to print "entered foo". Of course I could just hard-code the
string "foo" in a print statement, but I don't want to have the
function name written in more than one place.
 
M

Mathias Waack

Is there a way in Python to print the name of the function one is
currently in?
.... tb = traceback.extract_stack()
.... print tb[-1][2]f

I'm using a more comfortable way by setting a global debug flag and
enabling tracing (see sys.settrace). This gives you the same feature
without adding code to each function.

Mathias
 
S

Sean Ross

Russell Blau said:

Hi.

The posting that the above link refers to was made by me, but I'd like to
suggest that you do not use the code presented there (def WhoMightIBe()).
That was just a bit of a failed experiment to see whether I could track down
the name of a function _after_it_had_been_aliased_. What the OP wants is the
recipe (by Alex Martelli [1]) quoted in the posting I made previous to this
one. I regret posting that experiment now - It was fun to try, but I think
it casts more shadow than light.

Good luck,
Sean

[1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062
 

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,774
Messages
2,569,599
Members
45,173
Latest member
GeraldReund
Top