How do I get a function's name as a string?
def foo():
pass
>>> name_of(foo)
"foo"
How do I get a function's name as a string?
def foo():
pass
>>> name_of(foo)
"foo"
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.
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. :)
If you're interested in class methods too, Python 3.3+ has __qualname__ in addition to __name__.
def my_function():
pass
class MyClass(object):
def method(self):
pass
print(my_function.__name__) # gives "my_function"
print(MyClass.method.__name__) # gives "method"
print(my_function.__qualname__) # gives "my_function"
print(MyClass.method.__qualname__) # gives "MyClass.method"
import inspect
def foo():
print(inspect.stack()[0][3])
where
stack()[0] is the caller
stack()[3] is the string name of the method
I've seen a few answers that utilized decorators, though I felt a few were a bit verbose. Here's something I use for logging function names as well as their respective input and output values. I've adapted it here to just print the info rather than creating a log file and adapted it to apply to the OP specific example.
def debug(func=None):
def wrapper(*args, **kwargs):
try:
function_name = func.__func__.__qualname__
except:
function_name = func.__qualname__
return func(*args, **kwargs, function_name=function_name)
return wrapper
@debug
def my_function(**kwargs):
print(kwargs)
my_function()
Output:
{'function_name': 'my_function'}
import inspect
def my_first_function():
func_name = inspect.stack()[0][3]
print(func_name) # my_first_function
or:
import sys
def my_second_function():
func_name = sys._getframe().f_code.co_name
print(func_name) # my_second_function
Try
import sys
fn_name = sys._getframe().f_code.co_name
further reference https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html
You can get a function's name as a string by using the special __name__ variable.
def my_function():
pass
print(my_function.__name__) # prints "my_function"