Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the function name as a string in Python from inside that function

Tags:

python

def applejuice(q):
   print THE FUNCTION NAME!

It should result in "applejuice" as a string.

like image 453
TIMEX Avatar asked Oct 08 '09 20:10

TIMEX


4 Answers

This also works:

import sys

def applejuice(q):
    func_name = sys._getframe().f_code.co_name
    print func_name
like image 159
Jeff B Avatar answered Oct 15 '22 16:10

Jeff B


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

like image 30
Nope Avatar answered Oct 15 '22 18:10

Nope


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.

like image 7
John Millikin Avatar answered Oct 15 '22 16:10

John Millikin


Another way

import inspect 
def applejuice(q):
    print inspect.getframeinfo(inspect.currentframe())[2]
like image 3
JimB Avatar answered Oct 15 '22 17:10

JimB