In Python, how do I get a function name as a string, without calling the function?
def my_function():
pass
print get_function_name_as_string(my_function) # my_function is not in quotes
should output "my_function"
.
Is such function available in Python? If not, any ideas on how to implement get_function_name_as_string
, in Python?
Using
__name__
is the preferred method as it applies uniformly. Unlikefunc_name
, it works on built-in functions as well: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.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.will display the code in almost human readable format. :)
I like using a function decorator. I added a class, which also times the function time. Assume gLog is a standard python logger:
so now all you have to do with your function is decorate it and voila