views:

7952

answers:

3

In Python, How do I get the function name as a string without calling the function?

def my_function():
.
.
.


print get_function_name_as_string(my_function) # my_function is not in quotes
output => "my_function"

is this available in python? if not, any idea how to write get_function_name_as_string in python?

+13  A: 
my_function.func_name

There are also other fun properties of functions. Type dir(func_name) to list them. func_name.func_code.co_code is the compiled function, stored as a string.

import dis
dis.dis(my_function)

will display the code in almost human readable format. :)

MizardX
What is the difference between f.__name__ and f.func_name?
Federico Ramponi
They are the same. http://www.python.org/doc/2.5.2/ref/types.html#types
MizardX
double underscore names are traditionally regarded as private though never enforced. So it is better to use func_name even though they may be the same.
Sam Corder
Sam: __names are private, __names__ are special, there's a conceptual difference.
Matthew Trevor
+16  A: 
my_function.__name__

Using __name__ is the preferred method as it applies uniformly. Unlike func_name, it works on built-in functions as well:

>>> import time
>>> time.time.func_name
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'builtin_function_or_method' object has no attribute 'func_name'
>>> time.time.__name__ 
'time'

Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a __name__ attribute too, so you only have remember one special name.