13
def applejuice(q):
   print THE FUNCTION NAME!

It should result in "applejuice" as a string.

Mark Chackerian
  • 21,866
  • 6
  • 108
  • 99
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • 1
    See http://meta.stackexchange.com/questions/18584/how-to-ask-a-smart-question-on-so/25128#25128 – Lennart Regebro Oct 08 '09 at 20:39
  • 1
    From the answer you chose we can conclude that this was indeed a duplicate. Indeed, a question almost exactly the same name already existed: http://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python – Lennart Regebro Oct 08 '09 at 21:45
  • I disagree that this is a duplicate of #251464 -- it seems like this question is the inverse instead. – Mark Chackerian Nov 10 '12 at 19:09
  • What should it print in this case : `def applejuice(): print "thefunctionname"; orangejuice = applejuice; del applejuice; orangejuice();` – bruno desthuilliers Feb 25 '15 at 11:52

7 Answers7

22

This also works:

import sys

def applejuice(q):
    func_name = sys._getframe().f_code.co_name
    print func_name
Jeff B
  • 29,943
  • 7
  • 61
  • 90
11
def applejuice(**args):
    print "Running the function 'applejuice'"
    pass

or use:

myfunc.__name__

>>> print applejuice.__name__
'applejuice'

Also, see how-to-get-the-function-name-as-string-in-python

Community
  • 1
  • 1
Nope
  • 34,682
  • 42
  • 94
  • 119
8
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.

John Millikin
  • 197,344
  • 39
  • 212
  • 226
3

Another way

import inspect 
def applejuice(q):
    print inspect.getframeinfo(inspect.currentframe())[2]
JimB
  • 104,193
  • 13
  • 262
  • 255
2

You need to explain what your problem is. Because the answer to your question is:

print "applejuice"
Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
1

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/

0
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)