8

Possible Duplicate:
How to get the function name as string in Python?

I know that I can do that :

def func_name():
    print func_name.__name__

which will return the name of the function as 'my_func'.

But as I am into the function, is there a way to directly call it generically ? Something like :

def func_name():
    print self.__name__

In which Python would understand that I want the upper part of my code hierarchy?

Community
  • 1
  • 1
jlengrand
  • 12,152
  • 14
  • 57
  • 87
  • 1
    btw, `self` is not a magic keyword in Python, it's just a convention for naming the first parameter passed to an instance method (which is the instance to which the method is bound). – Wooble Sep 15 '11 at 14:29
  • 1
    I don't think there is any easy solution. Check this question http://stackoverflow.com/questions/5063607/is-there-a-self-flag-can-reference-python-function-inside-itself – rplnt Sep 15 '11 at 14:32
  • 1
    What do you plan to use the name for? – Mike Graham Sep 15 '11 at 14:34

4 Answers4

9

Not generically, but you can leverage inspect

import inspect

def callee():
    return inspect.getouterframes(inspect.currentframe())[1][1:4][2]

def my_func():
    print callee() // string my_func

Source http://code.activestate.com/recipes/576925-caller-and-callee/

John Giotta
  • 16,432
  • 7
  • 52
  • 82
6

AFAIK, there isn't. Besides, even your first method is not totally reliable, since a function object can have multiple names:

In [8]: def f(): pass
   ...: 

In [9]: g = f

In [10]: f.__name__
Out[10]: 'f'

In [11]: g.__name__
Out[11]: 'f'
NPE
  • 486,780
  • 108
  • 951
  • 1,012
5

You can also use the traceback module:

import traceback

def test():
    stack = traceback.extract_stack()
    print stack[len(stack)-1][2]


if __name__ == "__main__":
    test()
Femi
  • 64,273
  • 8
  • 118
  • 148
2

One possible method would be to use Decorators:

def print_name(func, *args, **kwargs):
   def f(*args, **kwargs):
      print func.__name__
      return func(*args, **kwargs)
   return f

@print_name
def funky():
   print "Hello"

funky()

# Prints:
#
# funky
# Hello

Problem with this is you'll only be able to print the function name either before or after calling the actual function.

Realistically though, since you're already defining the function, couldn't you just hardcode the name in?

Manny D
  • 20,310
  • 2
  • 29
  • 31