Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
get current function name in Python
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Note: This may only work in CPython. For more info please see python doc about sys._getframe
import sys
# This will also show that function name(co_name) in python is bounded to function code(f_code).
# i.e., function assignment will not change the attribute of "co_name", function name
def get_current_func_name():
“”Get current func name.”“”
print sys._getframe.f_code.co_name
# print "get_current_func_name"
get_current_func_name()
another_func = get_current_func_name()
# print "get_current_func_name"
another_func()
######################Inspect========================
# Note: This may only work in CPython. For more info please see python doc about inspect.currentframe
import inspect
def get_current_func_name():
“”Get current func name.”“”
cur_frame = inspect.currentfram()
try:
print cur_frame.f_code.co_name
finally:
del frame
# do not use below code to get the current frame. It will get all the frames back and then select
# current one.
# frames = inspect.stack()
# try:
# print frames[0][3]
# finally:
# del frames
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.