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'.

3
  • 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? Commented Aug 22, 2011 at 0: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. Commented Oct 20, 2011 at 0:55
  • This isn't always bad. unittest, for instance, uses the names of functions to detect which should be run. Commented Dec 11, 2012 at 7:24

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
+1 on the answer for the comment
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

Comments

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'

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.