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?

3
  • 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). Commented Sep 15, 2011 at 14:29
  • 1
    I don't think there is any easy solution. Check this question stackoverflow.com/questions/5063607/… Commented Sep 15, 2011 at 14:32
  • 1
    What do you plan to use the name for? Commented Sep 15, 2011 at 14:34

4 Answers 4

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/

Sign up to request clarification or add additional context in comments.

Comments

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'

Comments

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

Comments

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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.