Skip to content

Instantly share code, notes, and snippets.

@andyxning
Last active May 6, 2022 07:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyxning/3a747afd02ab52483666 to your computer and use it in GitHub Desktop.
Save andyxning/3a747afd02ab52483666 to your computer and use it in GitHub Desktop.
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