def applejuice(q):
print THE FUNCTION NAME!
It should result in "applejuice" as a string.
Mark Chackerian
23.8k7 gold badges116 silver badges106 bronze badges
asked Oct 8, 2009 at 20:21
TIMEX
275k369 gold badges805 silver badges1.1k bronze badges
7 Answers 7
This also works:
import sys
def applejuice(q):
func_name = sys._getframe().f_code.co_name
print func_name
answered Oct 8, 2009 at 20:33
Jeff B
30.1k7 gold badges64 silver badges91 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
def applejuice(**args):
print "Running the function 'applejuice'"
pass
or use:
myfunc.__name__
>>> print applejuice.__name__
'applejuice'
answered Oct 8, 2009 at 20:27
Nope
36.2k42 gold badges101 silver badges119 bronze badges
1 Comment
joel
this isn't from inside the function
import traceback
def applejuice(q):
stack = traceback.extract_stack()
(filename, line, procname, text) = stack[-1]
print procname
I assume this is used for debugging, so you might want to look into the other procedures offered by the traceback module. They'll let you print the entire call stack, exception traces, etc.
answered Oct 8, 2009 at 20:28
John Millikin
202k41 gold badges217 silver badges228 bronze badges
Comments
Another way
import inspect
def applejuice(q):
print inspect.getframeinfo(inspect.currentframe())[2]
answered Oct 8, 2009 at 20:31
Mr_Pink
110k17 gold badges287 silver badges275 bronze badges
Comments
You need to explain what your problem is. Because the answer to your question is:
print "applejuice"
answered Oct 8, 2009 at 20:23
Lennart Regebro
173k45 gold badges230 silver badges254 bronze badges
2 Comments
wilhelmtell
maybe he means: def func(anothah_func): print anothah_func's name
Lennart Regebro
Well, that's definitely possible. We'll see if he says what the problem is.
This site gave me a decent explanation of how sys._getframe.f_code.co_name works that returns the function name.
http://code.activestate.com/recipes/66062-determining-current-function-name/
1 Comment
Stephane Rolland
Wlecome to SO! please, think about providing explanation, and not only pointing to external links.
def foo():
# a func can just make a call to itself and fetch the name
funcName = foo.__name__
# print it
print 'Internal: {0}'.format(funcName)
# return it
return funcName
# you can fetch the name externally
fooName = foo.__name__
print 'The name of {0} as fetched: {0}'.format(fooName)
# print what name foo returned in this example
whatIsTheName = foo()
print 'The name foo returned is: {0}'.format(whatIsTheName)
answered Jun 26, 2013 at 23:59
Jonathan Kimball Galloway
1372 silver badges6 bronze badges
Comments
lang-py
def applejuice(): print "thefunctionname"; orangejuice = applejuice; del applejuice; orangejuice();