Last active
May 6, 2022 07:36
-
-
Save andyxning/3a747afd02ab52483666 to your computer and use it in GitHub Desktop.
get current function name in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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