How to get a function name as a string? How to get a function name as a string? python python

How to get a function name as a string?


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_nameTraceback (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.

To get the current function's or method's name from inside it, consider:

import inspectthis_function_name = inspect.currentframe().f_code.co_name

sys._getframe also works instead of inspect.currentframe although the latter avoids accessing a private function.

To get the calling function's name instead, consider f_back as in inspect.currentframe().f_back.f_code.co_name.

If also using mypy, it can complain that:

error: Item "None" of "Optional[FrameType]" has no attribute "f_code"

To suppress the above error, consider:

import inspectimport typesfrom typing import castthis_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_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 disdis.dis(my_function)

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