HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

How to get a function name as a string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfunctiongetnamestring

Problem

How do I get a function's name as a string?

def foo():
    pass

>>> name_of(foo)
"foo"

Solution

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 "", 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.

Code Snippets

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

Context

Stack Overflow Q#251464, score: 1422

Revisions (0)

No revisions yet.