TIMEX
TIMEX

Reputation: 272274

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

def applejuice(q):
   print THE FUNCTION NAME!

It should result in "applejuice" as a string.

Upvotes: 14

Views: 27894

Answers (7)

Sam Stephens
Sam Stephens

Reputation: 11

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/

Upvotes: 1

Nope
Nope

Reputation: 36010

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

Upvotes: 11

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)

Upvotes: 0

John Millikin
John Millikin

Reputation: 200986

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.

Upvotes: 8

Jeff B
Jeff B

Reputation: 30099

This also works:

import sys

def applejuice(q):
    func_name = sys._getframe().f_code.co_name
    print func_name

Upvotes: 22

Mr_Pink
Mr_Pink

Reputation: 109448

Another way

import inspect 
def applejuice(q):
    print inspect.getframeinfo(inspect.currentframe())[2]

Upvotes: 3

Lennart Regebro
Lennart Regebro

Reputation: 172367

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

print "applejuice"

Upvotes: 2

Related Questions