4

Possible Duplicate:
How do I get the name of a function or method from within a Python function or method?
How to get the function name as string in Python?

I have a function named func, I'd like to be able to get the functions name as a string.

pseudo-python :

def func () :
    pass

print name(func)

This would print 'func'.

Community
  • 1
  • 1
rectangletangle
  • 50,393
  • 94
  • 205
  • 275
  • 2
    Wanting to know the name of a function is often a sign of a suboptimal design. Why do you want to know the name it was defined with? How will you use it? Do you understand that a function is an object and can be treated like any other value in Python? – Mike Graham Aug 22 '11 at 00:53
  • In most cases I'd agree with you. In my particular case however, I was making a tool which would print out certain information about an arbitrary function. I wanted to have the name of the function in the print out. It wasn't in any form of structural position. – rectangletangle Oct 20 '11 at 00:55
  • This isn't always bad. unittest, for instance, uses the names of functions to detect which should be run. – dbn Dec 11 '12 at 07:24

3 Answers3

17

That's simple.

print func.__name__

EDIT: But you must be careful:

>>> def func():
...     pass
... 
>>> new_func = func
>>> print func.__name__
func
>>> print new_func.__name__
func
Daniel Naab
  • 22,690
  • 8
  • 54
  • 55
Umang
  • 5,196
  • 2
  • 25
  • 24
  • 9
    Also, a handy tip: simple questions like yours can very easily be answered by using the `dir` built-in function. e.g. `dir(func)` returns a list, with `'__name__'` as one of the items. – Umang Aug 22 '11 at 00:24
  • +1 on the answer for the comment – eyquem Aug 22 '11 at 00:29
2

A couple more ways to do it:

>>> def foo(arg):
...     return arg[::-1]
>>> f = foo
>>> f.__name__
'foo'
>>> f.func_name
'foo'
>>> f.func_code.co_name
'foo'
yurisich
  • 6,991
  • 7
  • 42
  • 63
2

Use __name__.

Example:

def foobar():
    pass

bar = foobar

print foobar.__name__   # prints foobar
print bar.__name__   # still prints foobar

For an overview about introspection with python have a look at http://docs.python.org/library/inspect.html

Ulrich Dangel
  • 4,515
  • 3
  • 22
  • 30